[英]How to check an integer isn't bigger than MAX_VALUE when bing parsed with Integer.parseInt()
I am writing a Java program that takes a number from a user and performs calculations on it.我正在编写一个 Java 程序,它从用户那里获取一个数字并对其进行计算。 I am taking the input with BefferedReader and I cannot use Scanner.我正在使用 BefferedReader 进行输入,但无法使用 Scanner。 The input string is parsed to an int value.输入字符串被解析为 int 值。
How can I check that the input string is not bigger than Integer.MAX_VALUE?如何检查输入字符串是否不大于 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.它会抛出一个 NumberFormatException 异常,我可以处理这个异常,但是对于任何以不同方式处理的非数字输入,它也会抛出异常。
default:
input.push(Integer.valueOf(input_string));
break;
One way would be to parse the value as a BigInteger
and then use intValueExact() to turn it into an int
:一种方法是将值解析为BigInteger
,然后使用intValueExact()将其转换为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
.如果值是非数字,则抛出NumberFormatException
,如果值太大或太小而无法存储在int
,则抛出ArithmeticException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.