PDA

View Full Version : error detection how to detect NaN infinity etc in java


Inquisit
09-01-2008, 10:15 PM
Question in Java

ive encountered a little challenge

ive tried to make my program detect an error

i.e such as NaN and then it displays a message dialog saying Syntax error

the problem is this works but the dialog keeps poping up when simple arithmetics are performed with proper answers NaN and Infinity
what i would like to achieve is just NaN or Infinity etc detected not everything

i.e
txtNumber1 ......N1
txtNumber2

sum=N1+N2

Answer=value of (sum);

i want the dialog to appear when Nan or Infinit appears in the Answer text
ive tried if but fails to detect it

i.e

if (sum).equals("NaN");
Messadialog appears saying syntax, math etc errors

||

if (sum).equals("Infinity");

Messadialog appears saying syntax, math etc errors user presses OK then refreshes the panel


this is where your expertise fits in :confused:

thanks

Fou-Lu
09-02-2008, 04:19 AM
I don't know of any numbers that can add up to NaN or Infinity, so I assume that this would be like if the user enters 'cat' or something like that right?
First, cast you're numbers and catch the exception tossed, then evaluate. I'd probably just throw on a check for it, but I have a feeling that Java may do that for you when you're trying to perform you're calculations. Its been a couple of years since I've done work in java (gotta get back into it though...), so I may be mistaken on that.

double d1, d2, result;
try
{
d1 = Double.valueOf(txtNumber1);
d2 = Double.valueOf(txtNumber2);
result = d1 + d2;
if (Double.isNaN(result))
{
throw new Exception('NaN result!');
}
if (Double.isInfinite(result))
{
throw new Exception('Result is Infinite');
}
}
catch (Exception ex)
{
// Do something, one of these didn't parse.
}

Another option is to let the method throw the exception, and catch it with you're main program. The advantage of this is that it forces the developer of the interface to gracefully handle the exceptions. Just add a throws Exception (or whatever exception type you want) as a part of you're method signature.

Ok, hope that helps!