java 判断字符串是否是整数

Java 中,如何判断字符串是否是整数呢?

有两种方式:

方式一:通过正则表达式

Java代码   收藏代码
  1. /*** 
  2.      * 判断 String 是否int 
  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.     }  

 上述方法不完善,不能识别负数,比如识别不了“-9”,“+9”。多谢大家指教,改进如下:

Java代码   收藏代码
  1. /*** 
  2.      * 判断 String 是否是 int 
  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.     }  

 测试代码如下:

Java代码   收藏代码
  1. @Test  
  2.     public void test_isInteger(){  
  3.         String input="123";  
  4.         System.out.println(input+":"+ValueWidget.isInteger(input) );  
  5.           
  6.         input="000000000000009";  
  7.         System.out.println(input+":"+ValueWidget.isInteger(input) );  
  8.           
  9.         input="-9";  
  10.         System.out.println(input+":"+ValueWidget.isInteger(input) );  
  11.           
  12.         input="-09";  
  13.         System.out.println(input+":"+ValueWidget.isInteger(input) );  
  14.           
  15.         input="--9";  
  16.         System.out.println(input+":"+ValueWidget.isInteger(input) );  
  17.     }  

 运行结果:

123:true

000000000000009:true

-9:true

-09:true

--9:false

 

 

 

方式二:通过java 的异常

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.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值