java中判断字符串是否为只包含数字?

一、用JAVA自带的函数

public static boolean isNumeric(String str){
  for (int i = 0; i < str.length(); i++){   
   if (!Character.isDigit(str.charAt(i))){
       return false;
     }
    }
  return true;
 }

二、用正则表达式

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

三、用ascii码判断

public static boolean isNumeric(String str){
   for(int i = 0; i < str.length(); i++){
      int chr=str.charAt(i);
      if(chr<48 || chr>57)
         return false;
   }
   return true;
}
全部评论

相关推荐

04-15 14:28
已编辑
Java
程序员小白条:学院+两段经典项目+技术栈,最大众的简历,纯看运气
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务