2012年8月7日 星期二

[ Java 代碼範本 ] 判斷字串是否為數字


參考自 這裡
- 用JAVA自帶的函數
  1. public  static  boolean  isNumeric(String str){   
  2.   for  ( int  i  =  0 ; i  <  str.length(); i ++ ){   
  3.    System.out.println(str.charAt(i));   
  4.    if  ( ! Character.isDigit( str.charAt(i))){   
  5.     return  false ;   
  6.    }   
  7.   }   
  8.   return  true ;   
  9. }  
- 用正則表達式
  1. package test.stlib;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. public class JudgeStrAsNum {  
  7.     public static void main(String[] args) {  
  8.         String intStrArry[] = {"1.0""-1.2""0.3""123.0""abc""a123"".12"};  
  9.         Pattern ptn = Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");  
  10.         Matcher mth = null;  
  11.         for(String intStr:intStrArry)  
  12.         {  
  13.             mth = ptn.matcher(intStr);  
  14.             if(mth.find())  
  15.             {  
  16.                 System.out.printf("\t[Info] %s is a number.\n", intStr);  
  17.             }  
  18.             else  
  19.             {  
  20.                 System.out.printf("\t[Info] %s is not a number.\n", intStr);  
  21.             }  
  22.                   
  23.         }  
  24.     }  
  25. }  
執行結果 :
[Info] 1.0 is a number.
[Info] -1.2 is a number.
[Info] 0.3 is a number.
[Info] 123.0 is a number.

[Info] abc is not a number.
[Info] a123 is not a number.
[Info] .12 is not a number.
This message was edited 3 times. Last update was at 16/08/2012 10:10:45

3 則留言:

  1. 方法2, 可能會有問題, 因為沒有判斷到 正負號和小數點.

    回覆刪除
    回覆
    1. 感謝你的回覆, 的確會有正負數與小數點的問題. 我有修改一下 Regex, 雖然解決了小數點與正負數, 但應該還是不夠嚴謹.

      刪除
  2. 作者已經移除這則留言。

    回覆刪除

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...