0

I am trying to have an input with only specific characters and spaces. The problem is that the Scanner is reading a non assign string, forcing it to loop. But it only happens/loops once.

I have tried input_nome = input.next(). However this way doesn´t let spaces to go on input.

public static final Scanner input = new Scanner(System.in);

int age = input.nextInt(); // This is the source of the problem!

System.out.print("Name: ");  
String input_nome;
while (true) {
    try {
        input_nome = input.nextLine();
        if (input_nome.matches("[a-zA-Z ]+")) {
            break;
        } else {
            System.err.print("Insert again: ");
        }
    } catch (Exception e) {
    }
}
    

I expect this output "Name: " But the actual output is this "Name: Insert again: "


SOLUTION

This problem happens when input.nextInt() is used previously. Just needed to use input.nextLine() in order to consume \n character. Like this:

...
System.out.print("Name: ");  
String input_nome;
input.nextLine(); // This clears the \n character
while (true) {
...

Explanation: https://stackoverflow.com/a/7056782/11860800

Grinnex.
  • 199
  • 3
  • 11

0 Answers0