Why this code goes into infinite loop?

6

Why do I put an invalid entry as asdf the code below goes into infinite loop?

After catching the exception and writing the message, should not it ask for another entry again?

import java.util.Scanner;

public class Leitura {
    public static void main (String[] argumentos) {
        int chute = -1, sorteado = 37;
        Scanner scanner = new Scanner(System.in);
        do {
            System.out.println("Insira um número:");
            try {
                chute = scanner.nextInt();
            } catch (Exception excecao) {
                System.out.println("Lol, loop infinito? Sem pedir outra entrada novamente?");
                System.out.println("O chute foi: " + chute + "\n");
            }
        } while (chute != sorteado);
    }
}
    
asked by anonymous 04.04.2014 / 05:22

2 answers

5

What is happening is that when you read an invalid value in nextInt() the read buffer is still stored in Scanner , causing an error in the next read, and then, and then ...

To resolve this, you should call a next() in order to clear the old buffer on failure:

try 
{
    chute = scanner.nextInt();
}
catch (Exception excecao) 
{
     scanner.next();
}
    
04.04.2014 / 05:41
5

To complement the response from @Lucas Nunes:

The value that is stored in the buffer of Scanner has the \n (enter) character you typed at the end of the last keyboard character reading, this causes Scanner interpret that you pressed enter in the next loop of the loop, generating an infinite loop.

By using scanner.next(); in catch , you "consume" the \n that was stored in buffer , so the buffer gets "clean "for the next reading.

    
04.04.2014 / 05:48