Reputation: 473
In Java, I am dividing by zero, which obviously does not produce a number.
public class tempmain {
public static void main(String args[])
{
float a=3/0;
System.out.println(a);
}
}
I expect the output to be "NaN", but it shows the following error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at tempmain.main(tempmain.java:6)
Is there any way (apart from if(denominator==0)
) by which NaN can be displayed?
Upvotes: 0
Views: 1289
Reputation: 20344
You are getting the unexpected ArithmeticException because of the way that your numeric literals 3 and 0 are treated. They are interpreted as integers, despite the fact that you assign a
to be a float. Java will interpret 3
as an integer, 3f
as a float and 3.0
or 3d
as a double. The division is performed as integer division and the result cast to a float. To see another interesting other effect of this - try float a = 1/3
and inspect a
- you will find it is 0.0, rather than 0.3333.... as you might expect.
To get rid of the Exception - change
float a = 3/0;
for
float a = 3f/0;
As others have noted in comments and answers, if you then print a
, you will see Infinity
rather than NaN
. If you really want to print NaN in this case, you can test a for being infinite i.e.
if (Float.isInfinite(a)) {
System.out.println("I want to print Infinity as NaN");
}
but I'd recommend against it as highly misleading - but I suspect that's not what you meant anyway
Upvotes: 7
Reputation: 2014
What about:
public class tempmain {
public static void main(String args[])
{
try {
float a=3/0;
System.out.println(a);
} catch (ArithmeticException x) {
System.out.println("Not Evaluable");
}
}
}
There is also this option:
{
...
//if (a != a) { // these two are equivalent
if (Float.isNaN(a)) {
System.out.println("NaN");
}
}
Upvotes: 2
Reputation: 127751
First, dividing by zero in floating point numbers does not give NaN, it gives infinity. Second, you're dividing integers, not floats.
float a = 3.0f/0.0f;
System.out.println(a); // Prints Infinity
Upvotes: 4