wild_o
wild_o

Reputation: 43

Why isn't this while loop condition stopping the loop?

System.out.println("Please enter your grades: ");    

while(scanner.nextInt() != -1){
            numbers.add(scanner.nextInt());
        }

I have a while-loop which is supposed to stop once a "-1" is entered by the user. Instead, a "-1" is inserted into my arraylist before being recognized. I would like to understand why the loop doesn't stop immediately upon detecting a "-1."

Upvotes: 0

Views: 55

Answers (2)

TaQuangTu
TaQuangTu

Reputation: 2343

Actually, You are typing input twice at each loop because scanner.nextInt() is called at two places in the while loop. Just call it one time and save typed value at each round. Below code does exactly what you want:

int nextInt;
while((nextInt = scanner.nextInt())!= -1){
    numbers.add(nextInt);
}

Upvotes: 0

Brian McCutchon
Brian McCutchon

Reputation: 8584

You're calling nextInt twice, and it returns a new int each time. Try this:

while(true){
    int val = scanner.nextInt();
    if (val == -1) {
        break;
    }
    numbers.add(val);
}

Upvotes: 2

Related Questions