我不确定为什么当我打印出来时,我的数组开头会出现 nullPointerException(请参阅最后一个 println)。我以前见过 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());
}
}
}