如何在java中将字符串转换为整数时检测溢出

时间:2012-02-26 06:23:44

标签: java

如果我想在java中将字符串转换为int 你知道我是否有办法检测溢出? 我的意思是字符串文字实际上代表一个大于MAX_INT的值?

java doc没有提到它.. 它只是说如果字符串不能被解析为整数,它将通过FormatException 没有提到关于溢出的话。

3 个答案:

答案 0 :(得分:9)

  

如果我想在java中将字符串转换为int,你知道我是否有办法检测溢出?

是。捕获解析异常将是正确的方法,但这里的难点是Integer.parseInt(String s)会为任何解析错误抛出NumberFormatException,包括溢出。您可以通过查看JDK的src.zip文件中的Java源代码进行验证。幸运的是,存在一个构造函数BigInteger(String s)将抛出相同的解析异常,除了用于范围限制异常,因为BigInteger没有边界。我们可以利用这些知识来捕获溢出情况:

/**
 * Provides the same functionality as Integer.parseInt(String s), but throws
 * a custom exception for out-of-range inputs.
 */
int parseIntWithOverflow(String s) throws Exception {
    int result = 0;
    try {
        result = Integer.parseInt(s);
    } catch (Exception e) {
        try {
            new BigInteger(s);
        } catch (Exception e1) {
            throw e; // re-throw, this was a formatting problem
        }
        // We're here iff s represents a valid integer that's outside
        // of java.lang.Integer range. Consider using custom exception type.
        throw new NumberFormatException("Input is outside of Integer range!");
    }
    // the input parsed no problem
    return result;
}

如果您确实需要为输入超过Integer.MAX_VALUE进行自定义,则可以在抛出自定义异常之前使用@ Sergej的建议进行此操作。如果上面的内容过大而你不需要隔离溢出的情况,只需通过捕获它来抑制异常:

int result = 0;
try {
    result = Integer.parseInt(s);
} catch (NumberFormatException e) {
    // act accordingly
}

答案 1 :(得分:0)

将String String值转换为Long并将Long值与Integer.Max_value

进行比较
    String bigStrVal="3147483647";        
    Long val=Long.parseLong(bigStrVal);
    if (val>Integer.MAX_VALUE){
        System.out.println("String value > Integer.Max_Value");
    }else
        System.out.println("String value < Integer.Max_Value");

答案 2 :(得分:0)

你不需要做任何事情。

作为Integer.parseInt(str, radix)状态的Javadoc,如果String表示的值不能表示为NumberFormatException值,则抛出int;即如果其幅度太大。这被描述为与str格式错误的情况不同的情况,所以很明显(对我而言)这就是我的意思。 (您可以通过阅读源代码来确认这一点。)