簡體   English   中英

試圖將兩個BigInterger Numbers一起添加到類構造函數中並獲取stackoverflow錯誤

[英]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方法調用在BigNumberadd時間。

這是第一個問題:

public BigNumber add(BigNumber other) throws CloneNotSupportedException {
    return ((BigNumber) BigNumber.this.CloneNumber()).add(other); 
}

您正在add方法中調用add ...您希望它如何工作?

目前尚不清楚為什么同時擁有sumsum2 ,但是我希望您的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方法
  • 遵循Java命名約定,其中方法是camelCased,而不是PascalCased。
  • 您應該刪除類中任何地方都沒有使用的sum2字段
  • 您無需在構造函數中添加任何內容-您只需:

     this.sum = new BigInteger(g); 
  • 您的字段稱為sum但顯然不是任何東西的總和-只是值。 我會將其重命名為value或類似名稱。

  • 目前尚不清楚為什么要這么做-您只是在復制BigInteger類的一小部分...為什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM