Java中怎样判断一个字符串是否是数字?

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}
}
}

posted @ 2016-07-07 11:02  Sunray0330  阅读(461)  评论(0编辑  收藏  举报