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)
1 ответ
Решение
Вы скрываете переменную в конструкторе. По телефону
BigInteger mTotientSum = BigInteger.ZERO;
вы только инициализируете локальную переменную mTotientSum и оставляете поле класса пустым.
Не объявляйте переменную в конструкторе. Вместо этого сделайте:
mTotientSum = BigInteger.ZERO;
Увидеть разницу?