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

 我来答
影视后期制作学习
2017-06-09 · 知道合伙人教育行家
影视后期制作学习
知道合伙人教育行家
采纳数:258 获赞数:697
荣获北京智泽苑教育科技有限公司金牌教师称号。

向TA提问 私信TA
展开全部
ava中判断字符串是否为数字的方法:

1.用JAVA自带的函数
public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}

2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}

3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false

Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null

上面三种方式中,第二种方式比较灵活。

第一、三种方式只能校验不含负号“-”的数字,即输入一个负数-199,输出结果将是false;

而第二方式则可以通过修改正则表达式实现校验负数,将正则表达式修改为“^-?[0-9]+”即可,修改为“-?[0-9]+.?[0-9]+”即可匹配所有数字。
动力节点
2017-04-21 · 口口相传的Java黄埔军校
动力节点
动力节点始于2009年,一家专注IT教育的培训机构,在全国各大城市设有直营校区,是中国软件研发人才一体化服务的倡导者,为解决当前软件开发技术飞速发展,专注培养面向互联网领域的IT高端软件人才
向TA提问
展开全部
用java的异常机制,不仅可以判断是否是数字,还可以判断整数或者小数:

public void checkInt(String bh){
try{
int num = Integer.parseInt(bh);//将输入的内容转换成int
System.out.println("是整数:"+num);//是整数
}catch (NumberFormatException e) {//转换成int类型时失败
try{
double d =Double.parseDouble(bh);//转成double类型
System.out.println("是小数:"+d);//是小数
}catch (NumberFormatException e2) {//转成double类型失败
System.out.println("不是数字");
}
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式