English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, você aprenderá diferentes métodos para verificar se uma string é um número em Java.
public class Numeric { public static void main(String[] args) { String string = "}}12345.15"; boolean numeric = true; try { Double num = Double.parseDouble(string); } catch (NumberFormatException e) { numeric = false; } if(numeric) System.out.println(string + " Is a number"); else System.out.println(string + " Is not a number"); } }
When running the program, the output is:
12345.15 is a number
No programa acima, temos uma string chamada string (String) que contém a string a ser verificada. Temos um valor booleano numeric que armazena o resultado final se for um número.
Para verificar se uma string contém apenas números, usamos o método parseDouble() da classe Double no bloco try para converter a string em Double
Se lançarmos um erro (ou seja, NumberFormatException), isso significa que a string não é um número e definimos numeric como false. Caso contrário, isso é um número.
No entanto, se precisarmos verificar várias strings, devemos convertê-lo em uma função. E a lógica é baseada em lançar exceções, o que pode ser muito caro.
Em vez disso, podemos usar as funcionalidades das expressões regulares para verificar se uma string é um número, conforme mostrado a seguir.
public class Numeric { public static void main(String[] args) { String string = "}}-1234.15"; boolean numeric = true; numeric = string.matches("-?\\d+(\\.\\d+)?" if(numeric) System.out.println(string + " Is a number"); else System.out.println(string + " Is not a number"); } }
When running the program, the output is:
-1234.15 is a number
In the above program, we use regex to check if the string is a number, rather than using try-catch block. This is done using the String's matches() method.
in the matches() method
-? Allow zero or more-for negative numbers in the string.
\\d+ Check if the string has at least1more numbers (\\d).
(\\.\\d+)? Allows zero or more of the given pattern (\\.\\d+) among
\\., check if the string contains a period (decimal point)
If so, it should at least follow one or more numbers \\d+.