NaN
If you run this, oops! You get a NullPointerException. That can be solved by initializing the integer array of tests defined in Performance to an empty array:
When rerunning the tests, you get a different exception:
NaN is a constant defined on both the java.lang.Float and java.lang.Double classes that means "Not a Number." If there are no scores, tests.length() returns 0, meaning you are dividing by zero in this line of code:
When it works with integers, Java throws an ArithmeticException to indicate that you are dividing by zero. With floating-point numbers, you get NaN, which is a legitimate floating-point number. Fix the problem by checking the number of test scores as the very first thing in average.
NaN has some interesting characteristics. Any boolean comparisons against NaN always result in false, as these language tests demonstrate:
You might want the average method to return NaN. But how would you write the test, since you cannot compare NaN to any other floating-point number? Java supplies the isNaN static method, defined on both Float and Double, for this purpose:
|
Tuesday, October 27, 2009
NaN
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment