java中判斷字符串是否為只包含數字


1.用Java自帶的函數

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

2.用正則表達式

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

3.用ascii碼判斷

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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM