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

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

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

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

是。 捕获解析exception将是正确的方法,但是这里的困难是Integer.parseInt(String s)任何解析错误抛出NumberFormatException ,包括溢出。 您可以通过查看JDK的src.zip文件中的Java源代码进行validation。 幸运的是,存在一个构造函数BigInteger(String s)将抛出相同的解析exception, 范围限制除外,因为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的输入自定义它,你可以在抛出自定义exception之前通过使用@ Sergej的建议来做到这一点。 如果上面是过度杀伤而你不需要隔离溢出的情况,只需通过捕获它来抑制exception:

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

将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"); 

你不需要做任何事情。

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