How can Java determine if a string is a number?

You can use regular expressions in Java to determine if a string is a number. Here is an example code:

public static boolean isNumeric(String str) {
    return str.matches("-?\\d+(\\.\\d+)?");  // 匹配整数或小数
}

public static void main(String[] args) {
    String str = "123.45";
    if (isNumeric(str)) {
        System.out.println("字符串是数字");
    } else {
        System.out.println("字符串不是数字");
    }
}

The isNumeric method in the code above uses the regular expression -?\\d+(\\.\\d+)? to determine whether a string is a number. If the string is an integer or decimal, it returns true; otherwise, it returns false.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds