2012-12-19 65 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];