校验数字的三种方式

判断数字的三种方式

方式一:使用Character.isDigit

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

 

方式二:(不推荐使用)

Java代码   收藏代码
  1. public static boolean isValidInt(String value) {  
  2.         try {  
  3.             Integer.parseInt(value);  
  4.         } catch (NumberFormatException e) {  
  5.             return false;  
  6.         }  
  7.         return true;  
  8.     }  
  9. /** 
  10.      * @param if the value is between -9223372036854775808 and 
  11.      *        9223372036854775807, then return true 
  12.      * @return 
  13.      */  
  14.     public static boolean isValidLong(String value) {  
  15.         try {  
  16.             Long.parseLong(value);  
  17.         } catch (NumberFormatException e) {  
  18.             return false;  
  19.         }  
  20.         return true;  
  21.     }  

 

 

方式三:通过正则表达式(推荐使用)

Java代码   收藏代码
  1. /*** 
  2.      * 判断 String 是否是 int<br>通过正则表达式判断 
  3.      *  
  4.      * @param input 
  5.      * @return 
  6.      */  
  7.     public static boolean isInteger(String input){  
  8.         Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(input);  
  9.         return mer.find();  
  10.     }  
  11.     public static boolean isDouble(String input){  
  12.         Matcher mer = Pattern.compile("^[+-]?[0-9.]+$").matcher(input);  
  13.         return mer.find();  
  14.     }  

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐