[英]BigInteger throws null pointer exception
我無法讓BigInteger為其添加另一個BigInteger。 任何建議相關代碼:
在課堂上宣布:
private BigInteger mTotientSum;
在構造函數中完成:
BigInteger mTotientSum = BigInteger.ZERO;
相對方法:
BigInteger totientMultiplier = BigInteger.valueOf(mTotientMulitplier);
for (long i = 1; i <= mMaxNum; i++)
{
BigInteger j = BigInteger.valueOf(i);
System.out.println(j.toString());
BigInteger num = j.multiply(totientMultiplier);
System.out.println(num.toString());
BigInteger totient = calculateTotient(num);
System.out.println(totient);
mTotientSum = mTotientSum.add(totient); //This is line 113
System.out.println("Sum at" + i + " = " + mTotientSum.toString());
}
我得到的輸出是:
1
510510
17
16
16
Exception in thread "main" java.lang.NullPointerException
at Totient.run(Totient.java:113) (Note that line 113 is noted above.)
at Totient.main(Totient.java:131)
你正在構造函數中隱藏變量。 通過電話
BigInteger mTotientSum = BigInteger.ZERO;
您只是初始化本地mTotientSum變量並將類字段保留為null。
不要在構造函數中重新聲明變量。 相反:
mTotientSum = BigInteger.ZERO;
看到不同?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.