英文:
How to check an integer isn't bigger than MAX_VALUE when bing parsed with Integer.parseInt()
问题
我正在编写一个Java程序,该程序从用户那里获取一个数字并对其进行计算。我正在使用BufferedReader来获取输入,而不能使用Scanner。输入字符串被解析为int值。
我该如何检查输入字符串是否超过了Integer.MAX_VALUE?
它会抛出一个NumberFormatException异常,我可以处理这个异常,但对于任何非数字输入,这也会抛出不同的异常,而我希望对其进行不同的处理。
default:
input.push(Integer.valueOf(input_string));
break;
英文:
I am writing a Java program that takes a number from a user and performs calculations on it. I am taking the input with BefferedReader and I cannot use Scanner. The input string is parsed to an int value.
How can I check that the input string is not bigger than Integer.MAX_VALUE?
It throws a NumberFormatException and I could handle this but that would also throw for any non-numberic input that would be handled differently.
default:
input.push(Integer.valueOf(input_string));
break;
</details>
# 答案1
**得分**: 0
一种方法是将该值解析为 [`BigInteger`](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html),然后使用 [intValueExact()](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#intValueExact--) 将其转换为 `int`:
```java
int i = new BigInteger(inputString).intValueExact();
如果该值为非数字,则会抛出 NumberFormatException
,如果该值过大或过小无法存储在 int
中,则会抛出 ArithmeticException
。
英文:
One way would be to parse the value as a BigInteger
and then use intValueExact() to turn it into an int
:
int i = new BigInteger(inputString).intValueExact();
This throws NumberFormatException
if the value is non-numeric, or ArithmeticException
if the value is too big or small to store in an int
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论