我在簡單的代碼中遇到了一些麻煩。假設這是一個程序,人們可以添加存儲在數組中的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代碼識別。 –
...這就是爲什麼我討厭'公共靜態的一切'。它可以從任何地方改變。 –
@ user1834218 Java不會自動調整數組大小。看看'ArrayList's。 –