我正在尝试编写一个小型 Java 类。我有一个名为 BigNumber 的对象。我编写了添加两个正数的方法,以及减去两个也是正数的其他方法。
现在我希望他们处理负数。所以我写了几个'if'语句,例如。
if (this.sign == 1 /* means '+' */) {
if (sn1.sign == 1) {
if (this.compare(sn1) == -1 /* means this < sn1 */ ) return sn1.add(this);
else return this.add(sn1);
}
等等
不幸的是,代码看起来很丑。就像一堆 if 和 else。有没有更好的方法来编写这种代码?
编辑
我不能只是这样做,this.add(sn1)
因为有时我想将正数添加到负数或将负数添加到负数。但是 add 只能处理正数。所以我必须使用基本的数学,例如:而不是将负数添加到负数,而是添加this.abs()
(数字的绝对值)sn1.abs()
并返回带有相反符号的结果。德鲁:这条线来自方法 _add。我使用这种方法来决定如何处理它收到的数字。发送他们添加方法?或者将它们发送到 subract 方法但顺序不同(sn1.subtract(this)
)?等等..
if (this.sign == 1) {
if (sn1.sign == 1) {
if (this.compare(sn1) == -1) return sn1.add(this);
else return this.add(sn1);
}
else if (wl1.sign == 0) return this;
else {
if (this.compare(sn1.abs()) == 1) return this.subtract(sn1.abs());
else if (this.compare(sn1.abs()) == 0) return new BigNumber(0);
else return sn1.abs().subtract(this).negate(); // return the number with opposite sign;
}
} else if (this.sign == 0) return sn1;
else {
if (wl1.sign == 1) {
if (this.abs().compare(sn1) == -1) return sn1.subtract(this.abs());
else if (this.abs().compare(sn1) == 0) return new BigNumber(0);
else return this.abs().subtract(sn1).negate();
} else if (sn1.sign == 0) return this;
else return (this.abs().add(wl1.abs())).negate();
}
如您所见 - 这段代码看起来很糟糕..