Search code examples
javaeclipsedivide-by-zero

Division by zero in Java with "IsInfinite" and "POSITIVE_INFINITY" or "NEGATIVE_INFINITY"


I'm a completely noob in java and I have to make this:

Write a program that asks for the introduction of the dividend and the divisor (both real numbers) and show the result of the division in the output. If the result is infinite, the screen must show the text “The result is infinite”. Use the IsInfinite method for the corresponding wrapper class (or the comparison with the constants POSITIVE_INFINITY and NEGATIVE_INFINITY for the corresponding wrapper class).

The main problem is that I don't know how to use the IsInfinite method or the constants method (others methods worked). I have been searching on internet but I didn't find a solution.

Can you help me please?

EDIT: I did this but I don't know if it is what EXACTLY I have to do.

import java.util.Scanner;

public class Exercise {

    public static void main(String[] args) {

        Scanner key=new Scanner(System.in);
        System.out.println("Dividend:");
        double dividend=key.nextDouble();
        System.out.println("Divisor:");
        double divisor=key.nextDouble();

        double x = dividend/divisor;
        if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
            System.out.println("The result is infinite");
        } else {
            System.out.println("The quotient is: " + dividend/divisor);
        }
    }
}

Solution

  • The code you have given worked for me.

    However, you might want to change these lines:

       double x = dividend/divisor;
       if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
    

    to this:

       Double x = dividend / divisor;
       if (x.isInfinite()) {
    

    Notice the capital D in Double. This is the wrapper class of the primitive double. This class contains the isInfinite method.