簡體   English   中英

如何從非靜態方法訪問作為我的實例變量的對象數組?

[英]How can i access array of objects which is my instance variable from a non static method?

即使我的構造函數已經實例化了對象數組,我的程序也會給我空指針。 為什么我得到異常? 這是我的代碼:當 main 方法運行比較行時,它給了我一個空指針異常。 我不能以這種方式訪問​​我的對象嗎?

class MPLTest{
int n;
MPL []std;
MPLTest(){
    System.out.println("Enter number of Standards: ");
    Scanner in = new Scanner(System.in);
    n=in.nextInt();
    MPL []std = new MPL[n];
    for(int i=0;i<n;i++){
        System.out.println("Enter the number of students for standard "+(i+1));
        std[i]=new MPL(i+1,in.nextInt());
    }

}
public static void main(String [] args){

    MPLTest test = new MPLTest();
    System.out.println("The standard scoring the highest total marks is "+test.findBestClass());

}
int findBestClass(){
    int best=0;
    for(int i=1;i<n;i++){
        if(std[i].findTotal()>std[best].findTotal()) //the exception is here
            best=i;
    }
    return best+1;
}

}

您會收到NullPointerException因為全局實例數組未在構造函數中初始化。 您已經在類中聲明了std[]但在構造函數中,您已經聲明了一個新的數組,它是一個本地數組,類型為MPL 要初始化實例數組,請替換該行

MPL[] std = new MPL[n]; //creates a local variable

std = new MPL[n]; //points to the global variable

這類似於使用實例變量int n 在構造函數中,你不要

int n = in.nextInt();

n = in.nextInt();

因為n已經聲明了。 以同樣的方式初始化數組。

MPL []std;
    MPLTest(){
        System.out.println("Enter number of Standards: ");
        Scanner in = new Scanner(System.in);
        n=in.nextInt();
→       MPL []std = new MPL[n];

這稱為陰影 塊內的std是一個局部變量,它隱藏了一個名稱相似但不同的名為std字段。

暫無
暫無

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

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