码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-07-07 12:37:04      阅读:164      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!