2013-06-16 3 views
0

BigInteger를 가져 와서 다른 BigInteger를 추가하는 데 문제가 있습니다.BigInteger가 null 포인터 예외를 throw합니다.

클래스로 선언 :

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

코드에 줄 번호를 추가하여 NPE의 원래 위치를 알려주십시오. –

+0

그것은 이미 언급되었습니다 ... – claydiffrient

+0

@EngineerDollery는'mTotientSum = mTotientSum.add (totient);'뒤에 코멘트를 봅니다. – Pshemo

답변

2

생성자에서 변수를 섀도 잉하고 있습니다.

BigInteger mTotientSum = BigInteger.ZERO; 

을 호출하면 로컬 mTotientSum 변수 만 초기화되고 클래스 필드는 null로 남습니다.

생성자에서 변수를 다시 선언하지 마십시오. 대신 다음을 수행하십시오.

mTotientSum = BigInteger.ZERO; 

차이점을 참조하십시오.

+0

와우, 고마워요 ... 30 분 동안 저 머리를 치고있었습니다. 나는 정상적인 것보다 더 나은 길을 안다. 이제 내 어리 석음은 영원히 그곳에 알려질 수있다. – claydiffrient

+1

@claydiffrient : 기꺼이 도와주었습니다. –

관련 문제