How to prevent the user to enter numbers for a given data?

Asked

Viewed 3,497 times

6

How do I make my Java program not accept numbers as given by the user?

I would like, in a field that requires the user name, if a number is inserted, such as a badge, make the program ask again for the name.

I’ve thought of several options like making a "number alphabet", but I don’t know if Java is the best option.

  • You are using swing, jsp, javafx, console or what?

  • 1

    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.

  • Using netbeans

  • 1

    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?

4 answers

7

One mode you can use to check whether or not a sequence contains certain characters is through regular expressions, in Java you can use the method String.Matches(), this method returns true if the sequence given as a parameter corresponds to a given regex.

In practice it would be something like this:

public boolean checkLetters(String str) 
{
    return str.matches("[a-zA-Z]+");
}

Example:

public Main()
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Digite o seu nome: ");
    String nome = sc.nextLine().trim();
    if (checkLetters(nome))
    {
        // Fazer alguma coisa aqui.
    }
    else
    {
        System.out.println("Neste campo não é permitido números. Tente Novamente.");
    }
}

Demonstration in Ideone.

5

You can create a unique method that takes as argument a String to be checked for numbers or not. For example:

public boolean hasNumbers(final String string){
   String numbers = "0123456789";
   for(char a : string.toCharArray())
     for(char b : numbers.toCharArray())
       if(a == b) return true;
   return false;
}

So you can use it in any application, be it Swing, console or web.


Console

Scanner input = new Scanner(System.in);
if(hasNumbers(input.nextLine())){
   // tem números, faz algo...
}

Swing

String input = textField.getText(); // pega o valor no jtextfield
if(hasNumbers(input)){
   // tem números, faz algo...
}

Test in Ideone.

See also the response from Qmechanic73 using regex.

4

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.

2

Only Put This On Keyreleased Event:

char[] text = txt.getText().toCharArray();

if (txt.getText().length() > 0){

    for (int i = 0; i < text.length; i++){
        if (text[i] >= '0' && text[i] <= '9'){
            txt.setText(txt.getText().replace(String.valueOf(text[i]), ""));
        }
    }
}

Since you use Netbeans it won’t be hard to add it, select the Textbox, go to events in the lower right corner and search for Keyreleased.

  • 7

    Your initial capitalization makes everything harder to read, don’t you think?

  • 1

    @bfavaretto I will probably try to leave this mania aside by the least here in the stack.

  • 1

    Do you use an extension to do this or is it manually with shift? Just out of curiosity.

  • @Renan In Fact Every Word I Tighten Caps Lock Is Instinctive And Fast.

  • 7

    Caracas, this kind of gives agony.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.