I'm making a simple calculator for this homework, and Java is returning "Infinity" when divided by 0.
I need to display some error message, when I get infinity. The problem is I don't know how to do the condition
double result; result = 4/0; //if result == infinity then some message - need help with this
The Double class in Java supports infinity. You can implement positive infinity or negative infinity.
The isInfinite() method of Java Float class returns a Boolean value for the specified float object or for 'v'. This method returns true if the argument passed is infinitely large in magnitude and returns false for finite floating-point arguments.
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) defines the NaN value. In Java, the floating-point types float and double implement this standard. Java defines NaN constants of both float and double types as Float.
You can use Double.isInfinite(double)
Here's double doc
The above code produces
ArithmeticException: / by zero
You can catch this exception in a try/catch block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With