我无法让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)
答案 0 :(得分:2)
您正在构造函数中隐藏变量。致电
BigInteger mTotientSum = BigInteger.ZERO;
您只是初始化本地mTotientSum变量并将类字段保留为null。
不要在构造函数中重新声明变量。而是做:
mTotientSum = BigInteger.ZERO;
看到区别?