java判断字符串是否为数字的方法小结

时间:2021-07-26 20:27:17

本文实例总结了java判断字符串是否为数字的方法。分享给大家供大家参考,具体如下:

方法一:用JAVA自带的函数

?
1
2
3
4
5
6
7
8
public static boolean isNumeric(String str){
 for (int i = str.length();--i>=0;){ 
  if (!Character.isDigit(str.charAt(i))){
  return false;
  }
 }
 return true;
}

方法二:用正则表达式

?
1
2
3
4
public static boolean isNumeric(String str){
  Pattern pattern = Pattern.compile("[0-9]*");
  return pattern.matcher(str).matches(); 
}

方法三:用ascii码

?
1
2
3
4
5
6
7
8
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;
}

希望本文所述对大家Java程序设计有所帮助。