我正在尝试根据给定的 JUnit 创建位置、长度和圆类,以便最终以图形方式输出它们。但是我现在被困在其中一种方法中好几天了。我试图截断精度,但后来我的 equals 方法失败了。
规模的 JUnit:
public void testScale(){
Length inch2 = Length.unit.scale(320.0);
assertTrue(inch2 != null);
assertEquals(Length.inch,inch2);
assertFalse(inch2.equals(Length.unit));
Length unit2 = Length.cm.scale(1.0/125.98425197);
assertTrue(unit2 != null);
assertEquals(Length.unit,unit2); // This is the line my scale method fails
// Here my unit2 has a length of 1.0001249999881234
// and my constant cm has a length of 1.0 but
// truncating those precisions caused my equals
// method to fails.
assertFalse(unit2.equals(Length.cm));
Length z = Length.meter.scale(0);
assertTrue(z != null);
assertEquals(Length.zero,z);
assertFalse(z.equals(Length.meter));
assertFalse(Length.zero.equals(null));
}
我的缩放方法:
public Length scale(double d) {
if (d < 0)
throw new IllegalArgumentException();
else {
return new Length(d* this.length);
}
}
我怀疑问题可能来自我的 equals 方法,但在给定的 JUnit 中它通过了测试。
用于等于的 JUnit:
public void testEquals(){
assertFalse(Length.unit.equals("Not a length"));
assertFalse(Length.inch.equals(null));
assertEquals(Length.zero,Length.unit.scale(0.0000001));
assertTrue(Length.unit.scale(0.0000001).compareTo(Length.zero) == 0);
assertTrue(Length.zero.compareTo(Length.unit.scale(0.0000001)) == 0);
assertFalse(Length.unit.scale(0.0000015).equals(Length.zero));
assertTrue(Length.unit.scale(0.0000015).compareTo(Length.zero) > 0);
assertTrue(Length.zero.compareTo(Length.unit.scale(0.0000015)) < 0);
}
我的等于方法:
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof Length)) {
return false;
}
Length o = (Length) other;
if (Math.abs(this.length - o.length) < 0.000001) {
return true;
} else {
return false;
}
}
请帮忙
我所有代码的链接: https ://www.dropbox.com/sh/bz400f8y0ufx381/59aUTilrBt