[英]Exception with Long.MAX_VALUE
我需要一种从文件(1 2 3 4 5)中读取数字并找到其总和的方法,如果总和大于 Long.MAX_VALUE。 它抛出一个异常。 问题:如何在方法本身中检查 Long.MAX_VALUE 和哪个 class 使用?
方法本身:
public static long findSum (String path) throws FileNotFoundException, AccessDeniedException, BadFormatException, MaxValueException, IOException {
String result1 = readFirstLine (new File ("C: \\ input.txt"));
String file1 = result1.replaceAll ("\\ s +", "");
long x = Long.parseLong (file1);
long i = 0;
while (x! = 0) {
i = i + x% 10;
x = x / 10;
if (i> Long.MAX_VALUE)
throw new MaxValueException ("The sum exceeds the permissible values of Long.MAX_VALUE");
}
return i;
使用Math.addExact(long x, long y)
(在 Java 8 中添加) :
返回其 arguments 之和,如果结果溢出 long 则抛出异常。
如果结果溢出很长,则抛出
ArithmeticException
i = Math.addExact(i, x % 10);
更新
由于我相信该代码的目的是反转long
值,因此您忘记将i
乘以10
,这意味着您还需要使用multiplyExact(long x, long y)
或multiplyExact(long x, int y)
(添加在 Java 9) 中:
i = Math.addExact(Math.multiplyExact(i, 10), x % 10);
如果文件内容为“1 2 3 4 5”,则x = 12345
, i = 15
(1+2+3+4+5)。
x >= i
总是正确的。
如果输入大量数字, Long.parseLong(file1)
将首先抛出NumberFormatException
。
所以你不需要检查i
。 你应该担心Long.parseLong(file1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.