简体   繁体   English

BigInteger抛出空指针异常

[英]BigInteger throws null pointer exception

I'm having trouble getting a BigInteger to add another BigInteger to it. 我无法让BigInteger为其添加另一个BigInteger。 Any suggestions The relevant code: 任何建议相关代码:

Declared in class: 在课堂上宣布:

private BigInteger mTotientSum; 

Done in constructor: 在构造函数中完成:

BigInteger mTotientSum = BigInteger.ZERO;

In relative method: 相对方法:

  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());
  }

The output I get is: 我得到的输出是:

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)

You're shadowing the variable in the constructor. 你正在构造函数中隐藏变量。 By calling 通过电话

BigInteger mTotientSum = BigInteger.ZERO;

you're only initializing a local mTotientSum variable and leaving the class field null. 您只是初始化本地mTotientSum变量并将类字段保留为null。

Don't re-declare the variable in the constructor. 不要在构造函数中重新声明变量。 Instead do: 相反:

mTotientSum = BigInteger.ZERO;

See the difference? 看到不同?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM