简体   繁体   中英

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

Since there will be multiple ingredients, I thought I should use an 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

You have instantiated ArrayList type of Ingredient (CLASS OBJECT) this ArrayList can only store Ingredient class object rather than individual attributes.

Ingredient is an object, so your ArrayList is basically a List of Ingredient objects. To add an Ingredient object to the ArrayList, you need to add the object to the list not individual values.

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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