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;
   }
 }
}

你可能感兴趣的:(Java)