Grinnex.
Grinnex.

Reputation: 1049

Java - Scanner doesn't read string with space (Solved)

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();
}

SOLUTION

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

Upvotes: 0

Views: 789

Answers (2)

user1478293
user1478293

Reputation: 46

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

Upvotes: 2

Puru
Puru

Reputation: 9

Please refer this link : Java Regex to Validate Full Name allow only Spaces and Letters

you can use the below Regular Expression

String regx = "^[\\p{L} .'-]+$";

This should work for all scenarios and unicode.

Upvotes: 1

Related Questions