2015-01-03 107 views
0

我仍然開始學習OOP,並且這個錯誤一直在我的代碼中彈出;說Exception in thread "main" java.lang.NullPointerExceptionNullPointerException java錯誤

public class SlumbookDriver{ 
    public static void main(String args[]){ 
     Slumbook[] contacts = new Slumbook[19]; 
     ... // index is an int and is the value of the index of the array 
     ... // i feed it to a function "void viewEntry" that just shows 
      // the other attributes of the class Slumbook 
     viewEntry(index, contacts); 
    } 
} 

然後我具備的功能VIEWENTRY

public static void viewEntry(int index, Slumbook[] contacts){ 
    Scanner sc = new Scanner(System.in); 
    if(index == 0){ 
     System.out.println("Array is empty"); 
    } 
    else{ 
     String id = contacts[index].getIdNo(); 
     System.out.println("Please enter ID number"); 
     String idNo = sc.next();  
     if(id != idNo){ 
      while(id != idNo && index != -1){ 
       index--; 
       id = contacts[index].getIdNo(); 
      } 
      if(index == -1){ 
       System.out.println("ID does not exist"); 
       return; //terminate action since the ID number does not exist 
      } 
     } 
     System.out.println(contacts[index].viewDetails()); 
    } 
} 
+0

你可以發佈更多的代碼,以及堆棧跟蹤打印與例外?這將有助於查明問題。 – Malt

回答

2

你只是初始化數組

Slumbook[] contacts = new Slumbook[19]; 

而不是它的內容,因此你會得到一個NullPointerException當您訪問數組元素,如下所示:

String id = contacts[index].getIdNo(); 

當您創建一個對象數組時,數組中的對象不會被初始化,您需要在使用它們之前使用new運算符初始化它們。類似這樣的:

contacts[index] = new Slumbook(); 
+0

是的,我已經做到了這一點,以填充另一個函數中的對象我的數組,但錯誤仍然彈出 – user253938

+0

@ user253938你可能不會持有適當的引用。發佈完整的代碼。 –

+0

謝謝,但它似乎只有索引變爲0時彈出錯誤(我不知道爲什麼它發生,雖然聯繫人[0]已分配值,所以它不能爲NULL),以解決它我只是保留接觸[0]爲空,離開程序,並開始與陣列上的聯繫人[1],現在它運行完美 – user253938

0

這裏的問題是你已經初始化了一個SlumBook數組,但是數組的內容需要初始化。 對於初學者來說,只是初始化內容:

for (int i = 0; i < contacts.length; i++) 
{ 
    contacts[i] = new SlumBook(); 
} 

做到這一點的方法viewEntry(int, SlumBook[])

0

一個NullPointerException發生在你試圖訪問一個字段或引用的方法使用接觸過,但該引用爲null 。

例如

Slumbook a = null; 
a.getIdNo(); // NullPointerException 

相同,如果你有一個數組

Slumbook [] data = new Slumbook[N]; 
data[i].getIdNo(); /// NPE 

第二個例子會拋出NPE如果包含在i位置的基準恰好是空發生。

當你得到一個異常堆棧跟蹤顯示,它包含文件名和確切行號(大部分時間)在異常發生