简体   繁体   English

使用扫描仪填充对象的ArrayList

[英]Using a Scanner to fill an ArrayList of objects

I was trying to fill an ArrayList of Ingredients , which are objects that store the name of the ingredient (a string), the price (a double), the number of calories (an integer) and if the ingredient is vegetarian (a boolean). 我正在尝试填充ArrayList of Ingredients ,这些对象存储了成分的名称(字符串),价格(双精度),卡路里的数量(整数)以及成分是否为素食主义者(布尔值) 。

Since there will be multiple ingredients, I thought I should use an ArrayList . 由于会有多种成分,我认为我应该使用ArrayList How do I fill the ingredient object with the data from the scanner? 如何用扫描仪中的数据填充原料对象? This is what I have so far: 这是我到目前为止的内容:

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);

Should be something like this 应该是这样的

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

Your Ingredient class should also have constructor that takes all four attributes 您的Ingredient类还应该具有采用所有四个属性的构造函数

You have instantiated ArrayList type of Ingredient (CLASS OBJECT) this ArrayList can only store Ingredient class object rather than individual attributes. 您已经实例化了成分的ArrayList类型(CLASS OBJECT),该ArrayList只能存储成分类对象,而不能存储单个属性。

Ingredient is an object, so your ArrayList is basically a List of Ingredient objects. 成分是一个对象,因此您的ArrayList基本上是成分对象的列表。 To add an Ingredient object to the ArrayList, you need to add the object to the list not individual values. 要将成分对象添加到ArrayList中,需要将对象添加到列表中,而不是单个值中。

Something like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM