[英]Using a Scanner to fill an ArrayList of objects
我正在嘗試填充ArrayList
of Ingredients
,這些對象存儲了成分的名稱(字符串),價格(雙精度),卡路里的數量(整數)以及成分是否為素食主義者(布爾值) 。
由於會有多種成分,我認為我應該使用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));
您的Ingredient類還應該具有采用所有四個屬性的構造函數
您已經實例化了成分的ArrayList類型(CLASS OBJECT),該ArrayList只能存儲成分類對象,而不能存儲單個屬性。
成分是一個對象,因此您的ArrayList基本上是成分對象的列表。 要將成分對象添加到ArrayList中,需要將對象添加到列表中,而不是單個值中。
像這樣:
ingredientArrayList.add(new Ingredient(ingredientName, pricePerOunce, numberOfCalories, isVegetarian));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.