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.
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.
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 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");
}