我正在尝试创建一个代表自然数的不可变类。我正在使用递归来处理Increment和Decrement方法。由于字段是final,我创建了一个私有构造函数,用于在递减/递增时为必要字段分配新值。在测试了这个实现后,我似乎无法确定问题所在。如果我递减100,它将是10.如果我增加99,它将是9.如果我增加/减少不在界限上的数字,我将得到一长串乱码。我想我需要朝着正确的方向轻推。如果它是可变的,我能够让它工作正常,因为我不必担心最后的字段。
public final class SlowBigNatural implements BigNatural{
final private int natural[];
final private int nSize;
final private int HIGHEST = 9;
public SlowBigNatural() {
this.nSize = 1;
this.natural = new int[1];
this.natural[0] = 0;
}
public SlowBigNatural(int p) {
this(Integer.toString(p));
}
public SlowBigNatural(String s) {
this.nSize = s.length();
this.natural = new int[nSize];
for (int i = 0; i < nSize; i++) {
this.natural[i] = Character.digit(s.charAt(i), 10);
}
}
public SlowBigNatural(BigNatural c) {
this(c.toString());
}
private SlowBigNatural(int[] natural, int nSize){
this.nSize = nSize - 1;
this.natural = new int[this.nSize];
for (int i = 0; i < this.nSize; i++) {
this.natural[i] = natural[i];
}
}
public BigNatural increment() {
int[] nClone = new int[nSize];
System.arraycopy(natural, 0, nClone, 0, nSize);
if (nSize == 1 || nClone[nSize - 1] != HIGHEST) {
nClone[nSize - 1]++;
BigNatural nInc = new SlowBigNatural(nClone.toString());
return nInc;
}
else {
nClone[nSize - 1] = 0;
BigNatural temp = new SlowBigNatural(nClone, nSize);
temp.increment();
return temp;
}
}
public BigNatural decrement() {
int[] nClone = natural.clone();
if (nClone[nSize - 1] != 0) {
nClone[nSize - 1]--;
BigNatural nDec = new SlowBigNatural(nClone.toString());
return nDec;
}
else {
if (nSize != 1) {
nClone[nSize - 1] = HIGHEST;
BigNatural temp = new SlowBigNatural(nClone, nSize);
temp.decrement();
return temp;
}
else{
BigNatural nDec = new SlowBigNatural(0);
return nDec;
}
}
}
public String toString() {
String nString = "";
for (int i = 0; i < nSize; i++) {
nString += String.valueOf(natural[i]);
}
return nString.replaceFirst("^0+(?!$)", "");
}
}
我介入了我的代码,当我将数组转换为字符串并将其传递给构造函数时,似乎发生了错误。它将阵列变成了一堆疯狂。继续调查。
答案 0 :(得分:1)
尚未完全研究过,但如果 SlowBigNatural 确实是正确不可变的,那么以下内容:
BigNatural temp = new SlowBigNatural(nClone, nSize);
temp.increment();
return temp;
就我所见,不太可能有用。上面对 temp.increment()的调用创建了一个你忽略的新对象,看到你返回 temp 本身而不是 temp.increment()的结果
您可以尝试将上述内容更改为:
BigNatural temp = new SlowBigNatural(nClone, nSize);
return temp.increment();
如果有效,请为减量()执行相同操作。