【问题标题】:Using a Scanner to fill an ArrayList of objects使用 Scanner 填充对象的 ArrayList
【发布时间】:2017-02-07 21:47:14
【问题描述】:

我试图填充Ingredients 中的ArrayList,它们是存储成分名称(字符串)、价格(双精度)、卡路里数(整数)以及如果成分是素食的(布尔值)。

由于会有多种成分,我想我应该使用ArrayList。如何使用来自扫描仪的数据填充成分对象?这是我到目前为止所拥有的:

public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    int numberOfIngredients = s.nextInt();
    List<Ingredient> ingredientArrayList = new ArrayList<Ingredient>();
    for (int i = 0; i< numberOfIngredients; i++){
        String ingredientName = s.next();
        double pricePerOunce = s.nextDouble();
        boolean isVegetarian = s.nextBoolean();
        int numberOfCalories = s.nextInt();
        ingredientArrayList.add(ingredientName, pricePerOunce, numberOfCalories, isVegetarian);
    }// ends for loop to fill the ingredientArray
}

【问题讨论】:

  • 您编写的代码有什么问题?此外,我们可能至少需要查看 Ingredient 类的构造函数来回答这个问题。
  • 您有一个成分对象列表,因此您只需创建并添加一个新成分对象。
  • 要提高插入ArrayList 的速度,请将成分数量传递给ArrayList constructornew ArrayList&lt;&gt;(numberOfIngredients)

标签: java arraylist java.util.scanner


【解决方案1】:
ingredientArrayList.add(ingredientName, pricePerOunce, numberOfCalories, isVegetarian);

应该是这样的

ingredientArrayList.add(new Ingredient(ingredientName, pricePerOunce, numberOfCalories, isVegetarian));

您的成分类还应该具有包含所有四个属性的构造函数

你已经实例化了 ArrayList 类型的成分(CLASS OBJECT),这个 ArrayList 只能存储成分类对象而不是单个属性。

【讨论】:

  • 谢谢!我不明白你所说的关于 instatiated arrayList 的第二部分是什么意思。它说“无法实例化类型成分”。这是什么意思?我认为通过存储成分类对象,我可以存储成分的属性(例如成分名称、每盎司价格、卡路里数、素食主义)。
  • 当您创建 List 时,您在编写 List 时定义了 List 以存储成分类型 OBJECT。因此列表只能存储对象列表,并且该对象必须是成分类对象。您首先要做的是尝试将成分属性存储到对象列表中。对象列表有很多对象,每个对象有很多属性关系
【解决方案2】:

Ingredient 是一个对象,因此您的 ArrayList 基本上是一个 Ingredient 对象的列表。要将成分对象添加到 ArrayList,您需要将对象添加到列表中,而不是单个值。

类似这样的:

ingredientArrayList.add(new Ingredient(ingredientName, pricePerOunce, numberOfCalories, isVegetarian));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多