-4

This is my program. I don't know where im dividing by zero so i cannot fix this error.

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

This program is supposed to reverse any number's digits. ex. 57823 --> 32875 I can't get that working.

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
    Have you ever looked at the exception stack trace? It exactly tells you what line of code causes the exception! See http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – isnot2bad Nov 24 '13 at 15:27
  • 1
    And also, this code has nothing to do with reversing a number. To do this you will need just a for and temp String. it will be something like just 3 lines of code. – Jorge Campos Nov 24 '13 at 15:30
  • Re-arrange your while loop logic. – Masudul Nov 24 '13 at 15:32
  • Show us what line throws the exception. – Radiodef Nov 24 '13 at 15:35

1 Answers1

2

Even if the stack trace would not tell you the line number where it happens, the error is easy to find. There are, in principle, only 3 occasions where you divide. Two of them are ok, as the power of something that is not 0 is hopefully never 0.

But your x variable in the totally mis-programmed while loop will take the following values:

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

And thus, using 0 as a second argument of % will cause the exception. Go, try it out.

BTW, if this did not happen, you would have an infinite loop, as the while depends on the value of n which doesn't change.

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • That's a good catch without the line number. OP, this is classic arithmetic overflow: https://en.wikipedia.org/wiki/Arithmetic_overflow – Radiodef Nov 24 '13 at 15:42