Reputation: 12637
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
Upvotes: 32
Views: 51283
Reputation: 31
Resurrecting a super old question because it came up in my Java class. So I'm sure you tried the try/catch like they all suggested, but you found, like me, that it didn't work with Double
. The try/catch with ArithmeticException doesn't work on Double
or Float
since they return "Infinity" instead of returning an exception. (note, delted myold "answer" since it wasn't an answer).
Piecing together a few different questions/answers on this, I came up with the following trials.
public class trial
{
public static void main(String[] args)
{
double a;
try {
a = 4/0;
System.out.println(" The answer is " +a);
} catch(ArithmeticException e) {
System.out.println(" You can't divide by zero. Please try again.");
}
}
}
The above code should give you the result "The answer is Infinity." At least it did for me since it is a double
.
With an int
, it would not need the below if
statement since it would throw an exception. But since it is a Double
, the if
statement below will cause it to throw an exception which the catch
will... well... catch.
public class trial
{
public static void main(String[] args)
{
double a;
try {
a = 4/0;
// if statement to throw an AtithmeticException if ans equals infinity
if(a == Double.POSITIVE_INFINITY){
throw new ArithmeticException();
}
else{
System.out.println(" The answer is " +a);
}
} catch(ArithmeticException e) {
System.out.println(" You can't divide by zero. Please try again.");
}
}
}
Upvotes: 1
Reputation: 1539
Jacek Kwiecień try this code
double result;
try{
result=4.0/0.0;
}catch(ArithmeticException e){
System.out.println("Math error "+ e.getMessage())
}
`
Upvotes: 0
Reputation: 88707
There are two fields for infinity in the Double
class: POSITIVE_INFINITY
and NEGATIVE_INFINITY
which you can check for.
Note that integer division by zero would throw an ArithmeticException
thus your line would have to be 4.0/0
, 4/0.0
or 4.0/0.0
since 4 and 0 are integers and thus result in integer math.
Upvotes: 2
Reputation: 15333
This kind of errors are called exceptions. You can use try-catch block to catch this exception.
try{
result = 4/0;
}
catch(ArithmeticException e){
System.out.println("You divided by zero");
}
you can read about exception handling here.
Upvotes: -1
Reputation: 533492
The above code produces
ArithmeticException: / by zero
You can catch this exception in a try/catch block.
Upvotes: 5
Reputation: 11403
Please see if it equal to Double.POSITIVE_INFINITY
double result;
result = 4.0 / 0.0;
Upvotes: 1