你可以用try{}catch来处理,如果转换的时候出错了,那就肯定不是数字
以下是个公共类:
public class CharTest {
public CharTest() {
}
public static void main(String args[]) {
String s = "123abc";
for (int i=0;i
System.out.println(ch + " is digit? " + Character.isDigit(ch));
System.out.println(ch + " is digit? " + (ch >= '0' && ch <= '9'));
}
}
}
以下使用正则表达式来验证
if(str==null || "".equals(str.trim())){
return true;
}
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str.trim());
if(isNum.matches()){
System.out.println("验证为数字");
}else{
System.out.println("验证不是数字");
}
1用JAVA自带的函数publicstaticbooleanisNumeric(Stringstr){for(inti=str.length();--i>=0;){if(!Character.isDigit(str.charAt(i))){returnfalse;}}returntrue;}2用正则表达式publicstaticbooleanisNumeric(Stringst