public class CheckIfNumeric {
public static void main(String[] args) {
String str1 = "12345";
String str2 = "12.34";
String str3 = "abc123";
System.out.println(isNumeric(str1)); // 输出: true
System.out.println(isNumeric(str2)); // 输出: true
System.out.println(isNumeric(str3)); // 输出: false
}
public static boolean isNumeric(String str) {
// 使用正则表达式判断字符串是否为数字
return str.matches("-?\\d+(\\.\\d+)?"); // 匹配整数或小数,允许负数
}
}
isNumeric
方法使用了正则表达式来判断字符串是否为数字。-?
:表示可选的负号。\\d+
:表示一个或多个数字字符。(\\.\\d+)?
:表示可选的小数部分,即小数点后跟一个或多个数字。因此,该方法可以正确识别整数、小数以及负数。如果字符串不符合这些规则,则返回 false
。
上一篇:java执行linux命令行
下一篇:java面向对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站