如何在使用Integer.parseInt()解析整数时检查该整数是否大于MAX_VALUE。

huangapple go评论58阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月14日 03:31:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64341960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定