Verify that the string contains only numbers

-3

How can I check if a string contains only numbers?

For example, you can not have * / = e etc ... only numbers.

Because I need to convert a string to int and if you type letters, symbols will generate an error.

    
asked by anonymous 15.12.2017 / 19:47

2 answers

4

One of the ways to know if the string contains only numbers is to use a regular expression

"1239417".matches("[0-9]+");   // true
"12312a".matches("[0-9]+");    // false
"12312+".matches("[0-9]+");    // false

In the regular expression [0-9]+

  • [ and ] : delimits a set of characters
  • 0-9 : the set of characters, any one between 0 and 9
  • + : of the defined expression, must match 1 or more groups
15.12.2017 / 20:00
2

Another way is to try converting to integer:

    String input = "123s";
    try {
        Integer.valueOf(input);
    } catch (Exception e) {
        System.out.println("Número inválido");
    }
    
21.12.2017 / 06:37