【发布时间】: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的速度,请将成分数量传递给ArrayListconstructor。new ArrayList<>(numberOfIngredients)
标签: java arraylist java.util.scanner