-3
package hw6;
import java.util.Scanner;
import java.util.ArrayList;

public class hw6q1 {

    public static void main(String[] args) {
        ArrayList<Integer> al = new ArrayList<Integer>();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter integers between 1 and 100 (enter 0 to 
stop):");
        while(input.nextInt() != 0){
            al.add(input.nextInt());
        }
        input.close();
        for(int i = 0; i < al.size(); i++){
            System.out.println(al.get(i));
        }



    }

}

So that is my code and when I run the program and give in the numbers 1 2 3 4 then 0 to end the loop it only prints 2 and 4. I was wondering why that is the case and how to fix it so that the arraylist gets all the number 1 2 3 and 4.

  • If you're calling `nextInt()` in your `while` condition and then **again** when adding it to your list, you basically throw away every other input. – QBrute May 05 '17 at 04:02

2 Answers2

1
while(input.nextInt() != 0){
    al.add(input.nextInt());
}

You have an int in your hand so you go into the loop where you ignore the int in your hand and then grab the next int and store it in the collection. You need to store that first int and store that in the ArrayList before asking for the next one.

e.g.

int num = input.nextInt();
while(num != 0)
{
    al.add(num);
    num = input.nextInt();
}
John3136
  • 28,809
  • 4
  • 51
  • 69
0

Each of the input.nextInt() will read an integer input.

Say you input the stream : 1 2 3 4 0

while(input.nextInt() != 0) { // Reads 1               | reads 3                | reads 0
    al.add(input.nextInt()); // Reads 2 and adds to al | reads 4 and adds to al
}
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27