Home > database >  Adding multiple objects with loop for java
Adding multiple objects with loop for java

Time:09-22

I'm trying to learn oop and couldn't find the solution for my problem. In this case I want to insert multiple food objects into an arraylist. The result I expected is when I input for example 3 into limiter, it should print whatever I input afterwards, instead it created some sort of extra object on index 0 as a blank.

Current output:

3
fried chicken
burger
[food: , food: fried chicken, food: burger]

Process finished with exit code 0

Expected output should be:

3
fried chicken
burger
sushi
[food: fried chicken , food: burger, food: sushi]

Process finished with exit code 0

Here is main:

package FoodRecommendation;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<food> arrayList = new ArrayList<>();

        int limiter = in.nextInt();
        for (int j = 0; j < limiter ; j  ) {
            arrayList.add(new food(in.nextLine()));
        }
        System.out.println(arrayList);
    }
}

and here is food:

package FoodRecommendation;

public class food {
    private String food;

    public food(String food) {
        this.food = food;
    }

    public String getFood() {
        return food;
    }

    @Override
    public String toString() {
        return "food: "   this.food;
    }
}

I do have an idea as to why this could happen, it's because when "(new food(in.nextLine()))" is inserted onto a loop it always creates a blank on index 0. But I just couldn't find the workaround for it. I hope someone could help me :D

CodePudding user response:

try to put

in.nextLine();

after

int limiter = in.nextInt();

in your code. The first one in your code is taking just "" as input.

  • Related