這段代碼有什么問(wèn)題呢?
public?class?Book?{ String?title; String?author; class?BooksTestDrive?{ } public?static?void?main(String?[]?args)?{ Book?[]?myBooks?=?new?Book[3]; int?x?=?0; myBooks[0].title?=?"The?Grapes?of?Java"; myBooks[1].title?=?"The?Java?Gatsby"; myBooks[2].title?=?"The?Java?Cookbook"; myBooks[0].author?=?"bob"; myBooks[1].author?=?"sue"; myBooks[2].author?=?"ian"; while?(x?<?3)?{ System.out.print(myBooks[x].title); System.out.print(?"by"?); System.out.println(myBooks[x].author); x?=?x?+?1; } } }
為什么沒有提示錯(cuò)誤,運(yùn)行的時(shí)候卻有問(wèn)題呢?
2016-05-02
對(duì)數(shù)組的初始化工作沒有結(jié)束,在Java中對(duì)非基本數(shù)據(jù)初始化時(shí),必須使用new。在使用new創(chuàng)建數(shù)組后,此時(shí)數(shù)組還是一個(gè)引用數(shù)組。只有再創(chuàng)建新的對(duì)象,并把對(duì)象賦值給數(shù)組引用,到此初始化結(jié)束。
可參考JAVA對(duì)象數(shù)組的初始化方法
public class Book {
? ? String title;
? ? String author;
? ? public static void main(String [] args) {
? ? ? ?Book[] myBooks = new Book[3];
? ? ??
? ? ? ?myBooks[0] = new Book();
? ? ? ?myBooks[1] = new Book();
? ? ? ?myBooks[2] =new Book();
? ? ? ?
? ? ? ? myBooks[0].title = "The Grapes of Java";
? ? ? ? myBooks[1].title = "The Java Gatsby";
? ? ? ? myBooks[2].title = "The Java Cookbook";
? ? ? ? myBooks[0].author = "bob";
? ? ? ? myBooks[1].author = "sue";
? ? ? ? myBooks[2].author = "ian";
? ? ? ? for(int x = 0; x < 3; x++ ){
? ? ? ? System.out.print(myBooks[x].title);
? ? ? ? System.out.print( " by " );
? ? ? ? System.out.println(myBooks[x].author);
? ? ? ? }
? ? }
? ? }