0

This is my program. I cannot find anything wrong with it, but when im trying to run it there is an error saying im dividing by zero.

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;
int 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 / (10^t)) - ((n /  (10 ^ (t+1))) * 10 )) * 10));
     } 
  println("The reverse number is " + total); 
   }  
}

I'm getting this error while trying to run it but I cannot find the problem.

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

1 Answers1

3

^ - is a XOR opertion, not degree! You need Math.pow(number, degree);

MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
  • Now i have another problem total = (total+((( n / (Math.pow(10, t))) - ((n / (Math.pow(10, (t+1)))) * 10 )) * 10)); "possible loss of precision" error – user3025598 Nov 23 '13 at 18:50
  • Yes, result of division in java have type "double". Change type of "total" to "double", or cast result of calculation to "int". – MartenCatcher Nov 23 '13 at 18:55
  • i really cant get that working... – user3025598 Nov 23 '13 at 18:59
  • i changed it to "double" but when i run it i get the / by zero error again! – user3025598 Nov 23 '13 at 19:06
  • i have no idea how it possible. Have you performed a complete stop a running program and restart it? – MartenCatcher Nov 23 '13 at 19:12
  • yeah i tried that. let me send u the code again – user3025598 Nov 23 '13 at 19:14
  • 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)); ... – user3025598 Nov 23 '13 at 19:15