Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide by Zero Exception with Typecaste (Java)

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.

like image 558
Kyle Joseph Green Avatar asked Feb 17 '26 03:02

Kyle Joseph Green


1 Answers

Here you are doing

(number * 10) /i !=0

where number is double.

Floating point numbers aren't recommended for comparisons because of the way they get stored (in mantissa and exponent form). So, if this condition returns true, consider yourself lucky.

Because of that your loop is kinda never-ending loop. The reason you are getting arithmetic exception though is that here you are multiplying i by 10 in this kinda infinite loop. "i" reaches "integer" limit of 32 bits and overflows and ultimately makes all those 32 bits as 0.

Effectively, i=0 and both of the following throw divide by zero exception

(number * 10) /i 

and

(number % i) - digit)/(i / 10)
like image 67
Neeraj Gupta Avatar answered Feb 20 '26 02:02

Neeraj Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!