I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris".
What happens with the code below is that the scanner input.next()
doesn't allow the mentioned example input string.
I expect this output: Success!
but this is the actual output: Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
The source of the problem is the used scanner method.
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
Explanation: https://stackoverflow.com/a/22458766/11860800
String t = "Chuck Norris";
t.matches("[a-zA-Z ]+")
Does in fact return true
. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s
. I also recommend 101regex.com