当 bing 用 Integer.parseInt() 解析时如何检查整数不大于 MAX_VALUE

How to check an integer isn't bigger than MAX_VALUE when bing parsed with Integer.parseInt()

我正在编写一个 Java 程序,它从用户那里获取一个数字并对其进行计算。我正在使用 BefferedReader 进行输入,但无法使用 Scanner。输入字符串被解析为一个 int 值。

如何检查输入字符串是否不大于 Integer.MAX_VALUE?

它会抛出一个 NumberFormatException,我可以处理这个异常,但对于任何非数字输入也会抛出异常,处理方式会有所不同。

default:
    input.push(Integer.valueOf(input_string));
    break;

一种方法是将值解析为 BigInteger and then use intValueExact() 以将其转换为 int:

int i = new BigInteger(inputString).intValueExact();

如果值为 non-numeric,则抛出 NumberFormatException,如果值太大或太小而无法存储在 int 中,则抛出 ArithmeticException