Skip to content
Advertisement

Why do I have to write twice to add an input in the Arraylist?

public static void main(String[] args) {
    List<String> arrayList = new ArrayList<>();
    Scanner input = new Scanner(System.in);
    do {
        System.out.println("Enter a product");
        String product = input.nextLine();
        arrayList.add(product);
    }
    while (!input.nextLine().equalsIgnoreCase("q"));

    System.out.println("You wrote the following products n");
    for (String naam : arrayList) {
        System.out.println(naam);
    }
}

I’m trying to get some input from the user and store them into arraylist. The problem is I have to write the item twice to add an item into the list. I can’t figure out why!

Advertisement

Answer

Every time you write readLine(), a line is read. In this loop,

do {
  System.out.println("Enter a product");
  String product = input.nextLine();
  arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));

There are two occurrences of readLine(), so two lines are read every iteration. The first line is always added to the list and not checked against q, and the second is never added to the list, and always checked against q.

You should only do nextLine once:

while (true) {
    System.out.println("Enter a product");
    String product = input.nextLine(); // only this one time!
    if (!product.equalsIgnoreCase("q")) {
        arrayList.add(product);
    } else {
        break;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement