<pre name="code" class="java">public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
这是利用JAVA自带的一个函数,把字符串拆分成数组,然后循环一个一个的检测,可以判断出结果。
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
这是利用正则表达式,如果不是0-9范围的数字,就可以检测出来,然后方法返回值给false,是范围内的返回值为true。
public static boolean isNumeric(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
}
这是根据ascii检测的,将字符串转数组,利用循环一个个检测,如果字符的ascii再48-57范围内,就是数字,如果不在范围内,就不是数字。
public static boolean isNumeric(String str){
try{
Integer.parseInt(str);
return true;
}catch(NumberFormatException e){
return false;
}
}
这是个人比较喜欢用的利用异常catch块判断,根据对象的方法判断,如果不对,可以抛出,防止程序崩溃,而且抛出的同时,给出提示。检测什么数值可以用什么对象,double等都可以。并且catch块嵌套在代码中也方便。