java - BigInteger 抛出空指针异常

标签 java exception biginteger

我无法通过 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 变量并将类字段保留为空。

不要在构造函数中重新声明变量。相反,请执行以下操作:

mTotientSum = BigInteger.ZERO;

看出区别了吗?

关于java - BigInteger 抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17138610/

相关文章:

java - 导出函数名

java - 当抛出未经检查的异常时,异常处理程序是否有办法输出参数?

java - java.math.BigInteger 的问题

c++ - C++ 中 BigInt 类的良好和基本实现

java - 使用 Java BigInteger 从 g^(xr) 和 x 计算 g^r

java - 更改引用或返回引用

java - 如何在 jersey 1.11 过滤器中添加自定义响应和中止请求

java - Spring Bean路径错误

android - 异常总是 NULL

wpf - 为什么我的 WPF DataGrids 之一会给出 "' EditItem' is not allowed for this view"异常?