[英]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.