【问题标题】:Not able to fix <Exception in thread "main" java.lang.ArithmeticException: / by zero> error [closed]无法修复 <Exception in thread "main" java.lang.ArithmeticException: / by zero> 错误 [关闭]
【发布时间】:2013-11-24 15:26:57
【问题描述】:

这是我的程序。我不知道我在哪里除以零,所以我无法修复这个错误。

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

这个程序应该反转任何数字的数字。 前任。 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); 
   }  
}

【问题讨论】:

  • 你看过异常堆栈跟踪吗?它准确地告诉您是哪一行代码导致了异常!见stackoverflow.com/questions/3988788/…
  • 而且,此代码与反转数字无关。为此,您只需要一个 for 和 temp 字符串。大概只有 3 行代码。
  • 重新安排你的 while 循环逻辑。
  • 告诉我们哪一行引发了异常。

标签: java exception zero divide


【解决方案1】:

即使堆栈跟踪不会告诉您行号它发生的位置,也很容易找到错误。 原则上,你只有 3 次分裂。 其中两个是可以的,因为不为 0 的东西的力量希望永远不会为 0。

但是您在完全错误编程的 while 循环中的 x 变量将采用以下值:

[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 的值,它不会改变。

【讨论】:

猜你喜欢
  • 2022-12-02
  • 1970-01-01
  • 2022-12-30
  • 2019-06-23
  • 1970-01-01
  • 2023-01-03
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多