Why does this code loop infinity?

Asked

Viewed 804 times

6

Because if I put an invalid entry like asdf the code below enters infinite loop?

After capturing the exception and writing the message he should not 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);
    }
}

2 answers

5


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

To solve this, you must call one next() in order to clean the old buffer in case of failure:

try 
{
    chute = scanner.nextInt();
}
catch (Exception excecao) 
{
     scanner.next();
}
  • Interesting. But I didn’t understand why the method next in this case does not ask the user to enter an entry again and only cleans the buffer (I proved it works)? Because if I put in place of chute = scanner.nextInt(); something like umaString = scanner.next(); it will ask the user to enter a string.

  • In that case yes, just the next() for String.

  • But why inside the catch does it not ask the user to enter a string? (This happens only inside Try).

  • Because in the catch Scanner buffer already has a \n stored. Then it’s past the next() without having to type anything. Now put two next() in the catch and see the difference.

5

To complement @Lucas Nunes' reply:

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

When using the scanner.next(); in the catch, you "consume" the \n which was stored in the buffer, thus, the buffer is "clean" for the next reading.

  • Interesting. Thanks for the compliment. But as I can see that the character that is impaling the thing is just the \n, how can I print the Unicode of it for me to see this situation?

  • You will find this answer on this OS port: http://stackoverflow.com/questions/14817727/access-internal-buffer-length-and-token-match-position-of-flex-scanner

Browser other questions tagged

You are not signed in. Login or sign up in order to post.