[英]trying to add two BigInterger Numbers together in a class Constructor and gettiing stackoverflow error
試圖將兩個BigInterger Number一起添加到類構造函數中,並得到stackoverflow錯誤。
導入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);
}
}
堆棧溢出不在您的構造函數中。 這是您的main
方法調用在BigNumber
上add
時間。
這是第一個問題:
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
類的一小部分...為什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.