配列を出力するときに、配列の先頭(最後のprintlnを参照)でnullPointerExceptionが発生する理由がわかりません。以前にnullPointExceptionを見たことがありますが、それは配列の最後にありました。なぜ最初なのかわかりません。さらに、誰かが例外を取り除くのを手伝ってくれるなら、私はそれをいただければ幸いです。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("Book.txt");
Scanner sc = new Scanner(file);
Book[] books = new Book[20];
int x = 0;
while(sc.hasNext()){
int id, year;
String name, author;
//scan data for each book and create new book object
id = Integer.valueOf(sc.next());
year = Integer.valueOf(sc.nextLine().trim());
name = sc.nextLine();
author = sc.nextLine();
books[x] = new Book(id, name, year, author);
x++;
}
for(Book b : books){
System.out.println(b.toString());
}
}
}