본문 바로가기

개발/Java

[Head First Java] Chapter3 연습문제 컴파일러가 되어봅시다. A문제

소스가 컴파일을 할 수 있는지 확인

문제 소스
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 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;
		}
	}
}
정답
class Books {
 String title;
 String author;
}

public class BooksTestDrive {
	public static void main(String[] args) {
		Books[] myBooks = new Books[3];
		myBooks[0] = new Books();
		myBooks[1] = new Books();
		myBooks[2] = new Books();
		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;
		}
	}
}


myBooks 배열에 대한 객체가 생성되어 있지 않아 객체 생성문을 추가함
출력 결과
The Grapes of Java by bob
The Java Gatsby by sue
The Java Cookbook by ian