簡體   English   中英

如何在此代碼中處理java.lang.NullPointerException

[英]How to handle java.lang.NullPointerException in this code

這是我的代碼,它拋出java.lang.NullPointerException我嘗試使用此站點上的其他類似主題來處理它,但它沒有用。

import java.math.BigInteger;
import java.lang.Long;


public class Tamrin7 {

    public static  BigInteger ZERO;
    public static  BigInteger ONE;
    public static  BigInteger TEN;
    public static void main(String[] args){

        BigInteger a = ZERO ;
        BigInteger b = ZERO ;
        BigInteger increment = ONE ;
        int counter = 0 ;
        int thirteen = 13;
        BigInteger bigInt = new BigInteger(String.valueOf(thirteen));
        while(counter != 10000){
            b = a.add(inverse(a))   ;
            if (b.remainder(bigInt) == ZERO)
                ++counter;
            a = a.add(increment);
        }//end of while

        String finall = b.toString();

        System.out.printf("the value of the 10000th number is %s :" , finall );


    }//end of main
    public static BigInteger inverse (BigInteger c){
        BigInteger inversedNum = ZERO ; 
        while (c != ZERO){
            inversedNum = inversedNum.multiply(TEN).add(c.remainder(TEN));
            c = c.divide(TEN);
        }//end of while
        return inversedNum ;
    }
}//end of class

您在哪里初始化這些:

public static  BigInteger ZERO;
public static  BigInteger ONE;
public static  BigInteger TEN;

我不認為您這樣做:

public static  BigInteger ZERO = BigInteger.ZERO;
public static  BigInteger ONE = BigInteger.ONE;
public static  BigInteger TEN = BigInteger.TEN;  

或者,如果您要import static則:

import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.TEN;

並刪除您的聲明。

還有這個:

new BigInteger(String.valueOf(thirteen));

有點哭:

BigInteger.valueOf(thirteen);

會做的很好。

那里:

public static  BigInteger ZERO;
public static  BigInteger ONE;
public static  BigInteger TEN;

看起來他們需要初始化 例如

public static  BigInteger ZERO = BigInteger.ZERO;

否則,它們只是聲明為對象引用,因此為null。

您在這里遇到幾個問題。

public static  BigInteger ZERO;
public static  BigInteger ONE;
public static  BigInteger TEN;

它們永遠不會用值初始化,這就是為什么首先獲得空指針的原因。 如果您希望這樣做,則應使用現有對象創建對象或提供對現有對象的引用。

像這樣:

public static final BigInteger ZERO = BigInteger.ZERO;
public static final BigInteger ONE = BigInteger.ONE;
public static final BigInteger TEN = BigInteger.TEN;

但是您應該只使用BigInteger.ZERO而不是在代碼中重新聲明它們。

另外,不要這樣做:

 BigInteger bigInt = new BigInteger(String.valueOf(thirteen));

BigInteger具有工廠方法,該方法可以使用普通int,而無需將其強制轉換為String。

像這樣:

 BigInteger bigInt = BigInteger.valueOf(thirteen);

您需要初始化零,一和十。

我認為您想執行以下操作:

public static final BigInteger ZERO = BigInteger.ZERO;
public static final BigInteger ONE = BigInteger.ONE;
public static final BigInteger TEN = BigInteger.TEN;

雖然您不需要將它們聲明為常量,但可以將它們聲明為常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM