How can Java determine if something is a number?
In Java, you can use the following method to determine if a string is a number:
- determines if there is a match between a string and a specified regular expression
- Pattern of one or more digits.
String str = "12345";
boolean isNumber = str.matches("\\d+"); // true
- converts a string to an integer
String str = "12345";
try {
Integer.parseInt(str);
boolean isNumber = true;
} catch (NumberFormatException e) {
boolean isNumber = false; // 转换失败,不是数字
}
- Convert a string to a double data type.
String str = "123.45";
try {
Double.parseDouble(str);
boolean isNumber = true;
} catch (NumberFormatException e) {
boolean isNumber = false; // 转换失败,不是数字
}
Options:
– Among them, methods 2 and 3 are suitable for determining integers and decimals, while method 1 can only determine integers.