2013-11-24 173 views
-3

這是我的程序。我不知道哪裏除以零,所以我無法修復這個錯誤。無法修復<線程中的異常「main」java.lang.ArithmeticException:/ by zero>錯誤

Exception in thread "main" java.lang.ArithmeticException:/by zero 

該程序應該反轉任何數字的數字。 ex。 57823 - > 32875 我無法工作。

import acm.program.*; 
public class ReverseDigits extends Program { 
public void run(){ 
println("This program reverses the digits in an integer."); 
int n = readInt("Enter a positive integer: "); 
int x = 10; 
int t = 1; 
double total = 0; 
//Finds the number of digits 
while (n > 0){ 
    while (n % x != 0) { 
     t = t + 1; 
     x = x * 10; 
} 
} 
//In case the number has one digit the new number is the same 
if(t == 1) { 
total = n; 
} 
//Creating the new number 
while (t > 1) { 
     t=t-1; 
     total = (total + (((n/(Math.pow(10, t))) - ((n/(Math.pow(10, (t+1)))) * 10)) * 10)); 
    } 
    println("The reverse number is " + total); 
    } 
} 
+4

你有沒有看過異常堆棧跟蹤?它完全告訴你哪行代碼會導致異常!請參閱http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – isnot2bad

+1

此外,此代碼與倒轉數字無關。要做到這一點,你只需要一個for和temp字符串。它會像3行代碼一樣。 –

+0

重新安排你的while循環邏輯。 – Masudul

回答

2

即使堆棧跟蹤不會告訴你行號它發生在哪裏,錯誤很容易找到。 原則上,只有3次劃分。他們的 兩個都OK,因爲事物的力量不是0就是希望永遠爲0。

但在你x變量完全錯誤編程while循環將採取以下值:

[10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 1410065408, 
1215752192, -727379968, 1316134912, 276447232, -1530494976, 1874919424, 1569325056, 
-1486618624, -1981284352, 1661992960, -559939584, -1304428544, -159383552, -1593835520, 
1241513984, -469762048, -402653184, 268435456, -1610612736, 1073741824, -2147483648, 
0] 

因此,使用0作爲%的第二個參數將導致異常。 去試試吧。

順便說一句,如果這沒有發生,你將會有一個無限循環,因爲while取決於不會改變的值n

+0

這是一個沒有行號的好機會。 OP,這是經典的算術溢出:https://en.wikipedia.org/wiki/Arithmetic_overflow – Radiodef

相關問題