尝试在类Constructor中一起添加两个BigInteger数字并获得堆栈溢出错误 import java.math.BigInteger;
public class BigNumber implements Cloneable {
BigInteger sum = BigInteger.valueOf(0);
BigInteger sum2 = BigInteger.valueOf(0);
BigNumber(String g) {
sum = sum.add(new BigInteger(g));
}
public String ToString() {
String a = "" + sum;
return a;
}
public Object CloneNumber() throws CloneNotSupportedException {
return super.clone();
}
public BigNumber add(BigNumber other) throws CloneNotSupportedException {
return ((BigNumber) BigNumber.this.CloneNumber()).add(other);
}
public static void main(String[] args) throws CloneNotSupportedException {
BigNumber g = new BigNumber("46376937677490009712648124896970078050417018260538");
BigNumber j = new BigNumber("37107287533902102798797998220837590246510135740250").add(g);
String f = j.ToString();
System.out.print(f);
}
}
答案 0 :(得分:3)
堆栈溢出不在构造函数中。当您的main
方法在add
上调用BigNumber
时。
这是第一个问题:
public BigNumber add(BigNumber other) throws CloneNotSupportedException {
return ((BigNumber) BigNumber.this.CloneNumber()).add(other);
}
您在add
方法中呼叫add
...您希望这会如何发挥作用?
目前尚不清楚为什么你同时拥有sum
和sum2
,但我希望你的add
方法只需要:
public BigNumber add(BigNumber other) throws CloneNotSupportedException {
return new BigNumber(sum.add(other.sum).toString());
}
...虽然您最好使用构造函数的重载来接受BigInteger
,此时您可以拥有:
public BigNumber add(BigNumber other) throws CloneNotSupportedException {
return new BigNumber(sum.add(other.sum));
}
构造函数(和字段声明)将如下所示:
// Personally I'd make the class final, but that's a different matter
public class BigNumber {
private final BigInteger value; // Renamed from sum - see below
public BigNumber(BigInteger value) {
this.value = value;
}
public BigNumber(String value) {
this(new BigInteger(value));
}
... methods ...
}
此外:
toString
方法,而不是引入自己的ToString
方法clone()
,而不是引入自己的CloneNumber
方法sum2
字段您无需在构造函数中添加任何内容 - 您只需:
this.sum = new BigInteger(g);
你的字段被称为sum
,但它显然不是任何东西的总和 - 它只是值。我会将其重命名为value
或类似的东西。
BigInteger
课程的一小部分......为什么?