![Java中怎样判断一个字符串是否是数字? Java中怎样判断一个字符串是否是数字?](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
1:正则表达式
public static void main(String[] args) {
String str = "123456456456456456";
boolean isNum = str.matches("[0-9]+");
System.out.println(isNum);
}
2:用类型转换
public static void main(String[] args) {
boolean bool = isNum("123456");
boolean bool2 = isNum("12b");
boolean bool3 = isNum("1234");
boolean bool4 = isNum("12345%8");
System.out.println(bool);
System.out.println(bool2);
System.out.println(bool3);
System.out.println(bool4);
}
private static boolean isNum(String str) {
try {
int num = Integer.valueOf(str);// 把字符串强制转换为数字
return true;// 如果是数字,返回True
} catch (Exception e) {
return false;// 如果抛出异常,返回False}
}
}