我试图填充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
}
ingredientArrayList.add(ingredientName, pricePerOunce, numberOfCalories, isVegetarian);
应该是这样的
ingredientArrayList.add(new Ingredient(ingredientName, pricePerOunce, numberOfCalories, isVegetarian));
您的成分类还应该具有采用所有四个属性的构造函数
您已经实例化了成分(类对象(的 ArrayList 类型,此 ArrayList 只能存储成分类对象,而不是单个属性。
成分是一个对象,所以你的 ArrayList 基本上是一个成分对象列表。要将成分对象添加到数组列表,您需要将该对象添加到列表中,而不是单个值。
像这样:
ingredientArrayList.add(new Ingredient(ingredientName, pricePerOunce, numberOfCalories, isVegetarian));