温馨提示×

如何在Java中使用isNumeric方法判断字符串

小樊
93
2024-08-21 02:53:23
栏目: 编程语言

您可以使用Apache Commons Lang库中的StringUtils类来判断一个字符串是否为数字。以下是一个示例代码:

import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        String str = "12345";
        
        if(StringUtils.isNumeric(str)) {
            System.out.println("The string is numeric");
        } else {
            System.out.println("The string is not numeric");
        }
    }
}

如果您不想使用第三方库,您也可以使用正则表达式来判断一个字符串是否为数字。以下是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String str = "12345";
        
        if(str.matches("-?\\d+(\\.\\d+)?")) {
            System.out.println("The string is numeric");
        } else {
            System.out.println("The string is not numeric");
        }
    }
}

这两种方法都可以有效地判断一个字符串是否为数字。

0