Assuming you’re using console, you can do something like this:
public static String lerNome(String mensagem, Scanner scanner) {
while (true) {
System.out.println(mensagem);
String lido = scanner.nextLine().trim();
if (lido.isEmpty()) {
System.out.println("Desculpe, você não digitou nada. Tente novamente.");
continue;
}
try {
new BigDecimal(lido);
System.out.println("Desculpe, mas " + lido + " é um número. Você deveria ter digitado um nome. Tente novamente.");
} catch (NumberFormatException e) {
return lido;
}
}
}
And then you would use this method so:
Scanner ent = new Scanner(System.in);
String nome = lerNome("Digite o nome.", ent);
This code shows the message Digite o nome.
and reads a user-readable line of text. If this line of text is blank or is a number, it gives an error message and does not exit the loop, asking the user to type again. Otherwise (not empty and not number), it accepts and returns the typed text.
You are using swing, jsp, javafx, console or what?
– Victor Stafusa
Here is no dislike, here is evaluation of the effort of the person to post and its usefulness and clarity. Just as there is no like (have on Facebook, why the content there is all irrelevant, people like or dislike things, like does not help anyone evolve, learn, so here the taste has no turn), It is not to vote for what you like or dislike and yes what is useful or not, whether it is clear or not.
– Maniero
Using netbeans
– Joao
Netbeans is just the environment in which you develop. The user does not use netbeans. Does the user enter the names as? And what exactly constitutes a valid name and an invalid name?
Pedro da Silva
is valid?12345
is valid?XN500$
is valid?Martelo Verde
is valid?– Victor Stafusa