[英]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.