1. 程式人生 > >Exception in thread "main" java.lang.NullPointerException報錯原因

Exception in thread "main" java.lang.NullPointerException報錯原因

今天寫了這麼一段程式碼:

class Books{
String title;
String author;
}

class BooksTestDrive{
public static void main(String [] args){
Books[] myBooks = new Books[3];
int x = 0;
myBooks[0].title = "java aaaa";
myBooks[1].title = "java bbbb";
myBooks[2].title = "java cccc";
myBooks[0].author = "AAAA";
myBooks[1
].author = "BBBB"; myBooks[2].author = "CCCC"; while(x<3){ System.out.print(myBooks[x].title); System.out.print(" writed by "); System.out.println(myBooks[x].author); x = x + 1; } } }
在eclipse上執行之後,丟擲異常Exception in thread "main" java.lang.NullPointerException。
經過反覆的檢查和查閱資料後發現原因是:

聲明瞭陣列後直接就引用物件變數,並沒有例項化陣列物件。修改原始碼如下:

class Books{
String title;
String author;
}

class BooksTestDrive{
public static void main(String [] args){
Books[] myBooks = new Books[3];
int x = 0;
//修改部分
 myBooks[0] = new Books();
 myBooks[1] = new Books(); 
 myBooks[2] = new Books();

myBooks[0].title = "java aaaa"
; myBooks[1].title = "java bbbb"; myBooks[2].title = "java cccc"; myBooks[0].author = "AAAA"; myBooks[1].author = "BBBB"; myBooks[2].author = "CCCC"; while(x<3){ System.out.print(myBooks[x].title); System.out.print(" writed by "); System.out.println(myBooks[x].author); x = x + 1; } } }