2012-12-19 66 views
0

我在簡單的代碼中遇到了一些麻煩。假設這是一個程序,人們可以添加存儲在數組中的Notes。我知道這段代碼很長,但希望有人能幫助我。Java快速數組錯誤

public class NoteOrganizer { 

    int action = 0; 
    public static Note[] myArray; 

    public static void addNotes(int num) 
    { 
     String note; 
     String date; 

     for(int z = 0; z <= num; z++) 
     { 
      Scanner getLi = new Scanner(System.in); 
      System.out.println("Please enter a note (max 140 characters): \n"); 
      note = getLi.nextLine(); 

      System.out.println("Please enter a date:\n"); 
      date = getLi.nextLine(); 

      Note test = new Note(); 
      test.id = z; 
      test.myNote = note; 
      test.date = date; 
      myArray[z] = test; // THE ERROR IS IN THIS LINE, NOT THE LINE MENTIONED BEFORE 

     } 
    } 

    public static void main(String[] args) 
     { 
     int action = 0; 

     int y = 0; 

     Scanner getLi = new Scanner(System.in); 
     System.out.println("Please press 1 to add notes, 2 to delete notes or 3 to view " 
       + "all notes:\n"); 
     action = getLi.nextInt(); 

     if(action == 1) 
     { 

      System.out.println("How many notes would you like to add: \n"); 
      int d = getLi.nextInt(); 
      //myArray = new Note[d]; 
      addNotes(d); 
      //System.out.println(myArray[0].print()); 

     } 
     else if(action == 3) 
     { 
      System.out.println(Arrays.toString(myArray)); 
     } 

    } 
} 

,我得到的錯誤是

Exception in thread "main" java.lang.NullPointerException 
    at note.organizer.NoteOrganizer.addNotes(NoteOrganizer.java:46) 
    at note.organizer.NoteOrganizer.main(NoteOrganizer.java:95) 
Java Result: 1 

我評論這行的錯誤是。

任何幫助是極大的讚賞。

感謝,

回答

1
public static Note[] myArray; 

myArray[z] = test; 

你沒有初始化數組,所以還是空。

一旦你知道你需要的長度(好像是num),則可以使用陣列之前做

myArray = new Note[num]; 

(看起來你已經有了這種效果的代碼,但是由於某種原因它被註釋掉了)。

5

您尚未初始化您的筆記數組。看來你已經註釋掉該行出於某種原因:

//myArray = new Note[d]; 
+1

沒有注意到該評論; +1代碼識別。 –

+0

...這就是爲什麼我討厭'公共靜態的一切'。它可以從任何地方改變。 –

+0

@ user1834218 Java不會自動調整數組大小。看看'ArrayList's。 –

1

你從來沒有設置myArray到任何東西,所以你不能寫進去。

您試圖通過寫入數組來自動擴展數組,但這在Java中不起作用。然而,ArrayList不支持寫入末(但不排除任何另外的),以及重新分配其內部的數組作爲neccessary:

ArrayList<Note> myList = new ArrayList<Note>(); 

然後,代替

myArray[z] = test; 

使用

myList.add(test); 

(它會自動追加到List的末尾,無論它在哪裏)

然後從列表中讀出

myList.get(index) 
0

您需要初始化數組,我建議使用類ArrayList中,這就像一個動態數組。

myArray = new Note[length];