How to prevent user from entering numbers for a given data?

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's name, if a number is inserted, such as a badge, do with what program reorder the name.

I have already thought of several options such as making a "alphabet of numbers", but I do not know if Java will be the best option.

    
asked by anonymous 14.12.2014 / 00:37

4 answers

6

One way you can use to check whether a string contains certain characters is through regular expressions, in Java you can use the String.Matches() , this method returns true if the given string parameter matches a given regex . p>

In practice it would look 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.");
    }
}

Demo on Ideone .

    
14.12.2014 / 03:47
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 like this:

Scanner ent = new Scanner(System.in);
String nome = lerNome("Digite o nome.", ent);

This code shows the message Digite o nome. and reads a line of text read from the user. If this line of text is blank or a number, it gives an error message and does not exit the loop, prompting the user to retype. Otherwise (not blank and not number), it accepts and returns typed text.

    
14.12.2014 / 01:21
4

You can create a unique method that takes as an argument the 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 at Ideone .

See also QMechanic73 response using regex .

    
14.12.2014 / 02:47
2

Only Put That In 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 will not be difficult to add it, select the Textbox, go to events in the lower right corner and search for KeyReleased.

    
14.12.2014 / 02:18