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:

  1. determines if there is a match between a string and a specified regular expression
  2. Pattern of one or more digits.
String str = "12345";
boolean isNumber = str.matches("\\d+"); // true
  1. converts a string to an integer
String str = "12345";
try {
    Integer.parseInt(str);
    boolean isNumber = true;
} catch (NumberFormatException e) {
    boolean isNumber = false; // 转换失败,不是数字
}
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds