import java.util.Scanner;
public class SumDigits {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// prompt the user to enter a value and store it as the integer called number
System.out.print("Enter an integer: ");
double number = Math.abs(input.nextDouble());
System.out.println("The sum of the digits is " + sumNumbers(number));
input.close();
}
public static int sumNumbers (double number)
{
int sum = 0;
for (int i = 10, digit = 0; (number * 10) /i !=0; i *= 10, digit = (int)((number % i) - digit)/(i / 10))
{
sum += digit;
}
return sum;
}
}
At runtime, I get the error message
Exception in thread "main" java.lang.ArithmeticException: / by zero
referring to line 25 (my for loop conditions).
The loop worked fine until I tried type casting digit's value to an int, and I'm not really certain why that would cause any part of the loop to divide something by zero. I've gone over all the possibilities regarding the conditions that use rational expressions and can't deduce a contingency wherein any denominator would be set to zero. I get this error regardless of what number is input. I would not have chosen to save number as a double at all if it were not for the fact that my professor provided a number whose value exceeds that which can be stored within an int in one of his test cases. The program ran fine prior to the type cast and provided the correct answer for all other test cases.