如果我想在java中将字符串转换为int
你知道我是否有办法检测溢出吗?
我的意思是字符串文字实际上代表一个大于 MAX_INT 的值?
java doc没有提到它..
它只是说如果字符串不能被解析为整数,它将通过 FormatException
没有提到溢出的话。
如果我想在java中将字符串转换为int,你知道我是否有办法检测溢出?
是的。捕获解析异常是正确的方法,但这里的困难在于Integer.parseInt(String s)抛出一个NumberFormatException
for any解析错误,包括溢出。您可以通过查看JDK中的Java源代码来验证src.zip
文件。幸运的是,有一个构造函数BigInteger(String s)这将抛出相同的解析异常,except对于范围限制的,因为BigInteger
s没有界限。我们可以利用这些知识来捕获溢出情况:
/**
* 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;
}
如果你确实需要定制这个only输入超过 Integer.MAX_VALUE,您可以在抛出自定义异常之前使用 @Sergej 的建议来执行此操作。如果上面的方法太过分了,并且您不需要隔离溢出情况,只需通过捕获异常来抑制异常:
int result = 0;
try {
result = Integer.parseInt(s);
} catch (NumberFormatException e) {
// act accordingly
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)