Lautaro Paskevicius
Lautaro Paskevicius

Reputation: 196

Scanner not working in loop

After testing, I found out that this little loop never ends:

Scanner scanner = new Scanner(System.in);

int c = 1;                                   // initialize variable
                                             // and then
while(c != 0){                               // as long as its not 0
    System.out.println("Enter a number: ");
    c = scanner.nextInt();                   // ask for a new value
}

This loop takes place in a simple program where I ask the user to enter numbers, store them, and when he enters '0', it returns the summation of all numbers. (I'm leaving the storing code apart, irrelevant to the problem)

This loop simply never ends, and in fact, I can't even enter a number.

EDIT : Apparently, running this loop while testing doesn't work. I tried it on a main() and it worked perfectly. Thanks for your answers!

Upvotes: 0

Views: 3081

Answers (1)

Grim
Grim

Reputation: 1986

A Scanner has a buffer, this buffer is first-in-last-out, that means if you like to enter a 20 you must press 20. Between 2 and 0 is a small pause and the scanner has no idea whenever more numerals following (you might like to enter a 205, so he is waiting for the next number).

To identify the end of the number, the scanner is waiting for some character that is not a number. A Enter is such a no-number indicating the end of the number you like to read using nextInt. Unfortunately a Enter is also a String that can be read.

If you enter 20Enter the 20 is part of the number but the Enter is part of a String but still in the buffer. So after 20 the buffer contains a Enter and this is not a number. Because that is not a number the second readInt is waiting forever!

What you can do is flush the buffer to flush the unwanted Enter.

Example:

int c = 1;                                   // initialize variable
                                             // and then
while(c != 0){                               // as long as its not 0
    Scanner scanner = new Scanner(System.in);// construct without buffer
    System.out.println("Enter a number: ");
    c = scanner.nextInt();                   // ask for a new value
}

Hope that helps

Upvotes: 2

Related Questions