运行java程序时出现的错误:" java.lang.NullPointerException”
代码是:classBooks{Stringtitle;Stringauthor;}publicclassBooksTestDrive{publicstaticvoidma...
代码是: class Books { String title; String author; } public class BooksTestDrive { public static void main(String [] args) { Books [] myBooks = new Books[3]; int x = 0; myBooks[0].title = "the Grapes of Java"; myBooks[1].title = "the Grapes of Java2"; myBooks[2].title = "the Grapes of Java3"; myBooks[0].author = "bob"; myBooks[1].author = "bob2"; myBooks[2].author = "bob3"; while(x < 3) { System.out.print(myBooks[x].title); System.out.print("by"); System.out.println(myBooks[x].author); x = x + 1; } } } 用javac编译通过,但是用java运行时就报错了: Exception in thread "main" java.lang.NullPointerException at BooksTestDrive.main(BooksTestDrive.java:10) 不知道是哪里出错了啊???
展开
1个回答
2013-09-11
展开全部
你好,你的程序有如下问题: 1、Books [] myBooks = new Books[3] 这句只是声明并实例化了一个数组,但是数组里的对象并没有被实例化,因此下面要对每个数组里的对象进行实例化:myBooks[0] = new Books(); 2、这样改程序就可以运行了,但是你这样写破坏了Books类的封装性,不是面向对象编程所提倡的,不建议你这样写。你应该在Books类中加入setter,getter方法用于给title, author属性赋值和获取值。 修改后的完整代码如下: public class Books { public String title; public String author; /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the author */ public String getAuthor() { return author; } /** * @param author the author to set */ public void setAuthor(String author) { this.author = author; } } public 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].setTitle("the Grapes of Java"); myBooks[1].setTitle("the Grapes of Java2"); myBooks[2].setTitle("the Grapes of Java3"); myBooks[0].setAuthor("bob"); myBooks[1].setAuthor("bob2"); myBooks[2].setAuthor("bob3"); while (x < 3) { System.out.print(myBooks[x].getTitle()); System.out.print(" by "); System.out.println(myBooks[x].getAuthor()); x = x + 1; } } }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询