这篇文章给大家分享的是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中判断字符串是否为数字的方法,具体使用情况还需要大家自己动手实验使用过才能领会。如果想了解更多相关内容,欢迎关注亿速云行业资讯频道!