'Hello, i have an problem with an with a keyboard input program

When I type the name, it gives me a valid number or a special character. I would like to make it so that the number is not taken into account and is not returned, or maybe it gives an error message.

if (nome != null && !nome.isEmpty()) {
    System.out.println("Il nome inserito è:" + nome);
} else {
    System.out.println("Non è un nome valido");
}

while (!nome.contains("\[0-9\]+")) {
    continue;


Solution 1:[1]

String#contains() checks plain text; it doesn't do a regex match.

To do a regex match use String#matches(), but note that it requires the entire String to match.

The closest working code to yours is:

while (!nome.matches(".*\\d.*"))

If you want to allow only Latin letters and spaces, consider using:

nome.matches("(?i)[a-z ]+") // (?i) means ignore case

However your messages suggest you are in the context of Italian, so this may be more useful:

nome.matches("(?i)[a-il-vzàèéìòù ]+") // ignore case, jkwxy omitted, add accented vowels

The complete code would look like:

Scanner scanner = new Scanner(System.in);
String nome = null;
while (true) {
    System.out.println("Inserisci il nome:");
    nome = scanner.nextLine();
    if (!nome.matches("(?i)[a-il-vzàèéìòù ]+")) {
        System.out.println("Non è un nome valido");
        continue;
    }
}
System.out.println("Il nome inserito è: " + nome);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1