Float和Double包括float和double,有
NEGATIVE_INFINITY
-0.0
0
0.0
POSITIVE_INFINITY
和
NaN
与NaN进行比较,结果都是false。
所以尽量把“targeted执行的语句”放在确定的判断中,并且该判断返回true(因为NaN参与的判断一律返回false)
public employee(float monthly_salary)
{
if (monthly_salary >= 0.0)
{
this.yearly_salary = 12.0 * monthly_salary; // targeted执行的语句
}
else throw IllegalArgumentException("illegal monthly salary");
}
而下面的代码因为没有考虑monthly_salary等于NaN的情况,而不正确:
public employee(float monthly_salary)
{
if (monthly_salary < 0.0)
throw IllegalArgumentException("illegal monthly salary");
this.yearly_salary = 12.0 * monthly_salary; // targeted执行的语句在外面
}
参考:
http://blog.csdn.net/jierui001/article/details/3278382
除此以外,在对浮点型进行处理时,可以参照Princeton的代码:
public Point2D(double x, double y) {
if (Double.isInfinite(x) || Double.isInfinite(y))
throw new IllegalArgumentException("Coordinates must be finite");
if (Double.isNaN(x) || Double.isNaN(y))
throw new IllegalArgumentException("Coordinates cannot be NaN");
if (x == 0.0) this.x = 0.0; // convert -0.0 to +0.0
else this.x = x;
if (y == 0.0) this.y = 0.0; // convert -0.0 to +0.0
else this.y = y;
}
以及
public Interval1D(double min, double max) {
if (Double.isInfinite(min) || Double.isInfinite(max))
throw new IllegalArgumentException("Endpoints must be finite");
if (Double.isNaN(min) || Double.isNaN(max))
throw new IllegalArgumentException("Endpoints cannot be NaN");
// convert -0.0 to +0.0
if (min == 0.0) min = 0.0;
if (max == 0.0) max = 0.0;
if (min <= max) {
this.min = min;
this.max = max;
}
else throw new IllegalArgumentException("Illegal interval");
}