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);
}
}
Interesting. But I didn’t understand why the method
nextin 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 ofchute = scanner.nextInt();something likeumaString = scanner.next();it will ask the user to enter a string.– GarouDan
In that case yes, just the
next()for String.– Lucas Lima
But why inside the catch does it not ask the user to enter a string? (This happens only inside Try).
– GarouDan
Because in the
catchScanner buffer already has a\nstored. Then it’s past thenext()without having to type anything. Now put twonext()in thecatchand see the difference.– Lucas Lima