zoukankan      html  css  js  c++  java
  • java中如何判断一个String 是否可以强制转换成Integer

    简述

    项目中有时候需要判断一个String 的字符串能不能转换成 int,我在搜索引擎上搜索到时候发现有人问过同样的问题,但是回答者会有String 怎么能转换成Integer 的疑问,这里标注一下,同时也为了以后自己看到时候不要引起误导。这里说的是,例如 String str1 = 123 或者 String str2 = 0.44 这样的String, 可以说它们是String 类型的数字。

    解决方法 

    方法一:正则表达式

                 我们可以通过正则表达式,判断接收到的String 中有没有字母从而来判断这个String 能否转换成 int,这里就不把正则表达式附上了,网上有很多,毕竟菜鸟,自己写怕遗漏了什么。。

    方法二:StringIndexOutOfBoundsException 异常

                 当把不能转换成 int 的String 强制转换的时候,会抛出 StringIndexOutOfBoundsException 异常,我们可以将错就错,利用这个异常,即,如果抛出了此异常则 该String 不能转换成 int,否则可以。

    String date = 201311;
    
    try {
    
        int year =Integer.valueOf(date.substring(0, 4));
    
        int month=Integer.valueOf(date.substring(4,6));
    
        // 如果没抛出异常,则 date 可以正确转换成 int
    
    
    
    }catch(StringIndexOutOfBoundsException e){
    
        // 如果抛出异常,则 date 不能转换成 int
    
    }
    
    
    

    但这种靠异常来判断的做法感觉不是很好。

    方法三:工具类 NumberUtils(推荐) 在 commons-lang.jar 中,有个Util 类, NumberUtils,其中包括两个方法:

    1.
    
    NumberUtils.isDigits(String str)
    
    
    
    Checks whether the String contains only digit characters.
    
    
    
    Null and empty String will return false.
    
    
    
    Parameters:
    
    str the String to check
    
    Returns:
    
    true if str contains only Unicode numeric
     
    2.
    
    NumberUtils.isNumber(String str)
    
    
    
    Checks whether the String a valid Java number.
    
    
    
    Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
    
    
    
    Null and empty String will return false.
    
    
    
    Parameters:
    
    str the String to check
    
    Returns:
    
    true if the string is a correctly formatted number

    正如描述中说的:

                 NumberUtils.isDigits(str)     //判断str是否整数, true-整数  false-非整数
                 NumberUtils.isNumber(str)  //判断str是否数字(整数、小数、科学计数法等等格式)

             自己写正则表达式担心出错的同学可以试试这个工具类,虽然 工具类也是人写的也可能出错,但发布出来,用的人多,估计有错误也会更快被发现,如果还不放心也可以先看看其中的源码。

    另外,commons-lang.jar 除了包含这一个 Utils 之外还有很多,如 ArrayUtils,BooleanUtils,CharSequenceUtils 等,在此不一一列举。commons-lang.jar 的下载地址可以到

    下载

  • 相关阅读:
    存储过程生成POCO
    Asp.net MVC4与Razor呈现图片的扩展
    Html5中新input标签与Asp.net MVC应用程序
    HTML5上传文件显示进度
    JQuery图表插件之Flot
    用Html5与Asp.net MVC上传多个文件
    TSQL列出最后访问的存储过程
    Asp.net MVC 限制一个方法到指定的Submit按钮
    VisualStudio2012轻松把JSON数据转换到POCO的代码
    Apache Tika源码研究(三)
  • 原文地址:https://www.cnblogs.com/yuxiaoqi/p/3422304.html
Copyright © 2011-2022 走看看