java判断string是否为数字的方法

java判断string是否为数字的方法,第1张

java判断string是否为数字的方法

java中判断字符串是否为数字的方法:

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

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

语法

public char charAt(int index)

参数:index -- 字符的索引。

返回值:返回指定索引处的字符。

isDigit() 方法用于判断指定字符是否为数字。

语法:public static boolean isDigit(char ch)

参数:ch -- 要测试的字符。

返回值:如果字符为数字,则返回 true;否则返回 false。

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");

更多java知识请关注java基础教程栏目。

以上就是java判断string是否为数字的方法的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/688820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存