首页 > 编程语言 > 详细

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

时间:2016-07-07 12:34:07      阅读:290      评论:0      收藏:0      [点我收藏+]

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

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

原文:http://www.cnblogs.com/CAOXIAOYANG/p/5649316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!