我不知道爲什麼我打印出來時,在我的數組開頭出現nullPointerException(請參見上一個println)。我以前見過一個nullPointException,但它在數組的末尾。我不明白爲什麼它在一開始。另外,如果有人能幫助擺脫這個例外,我將不勝感激。在數組的開頭獲取NullPointerException?
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());
}
}
}
你怎麼知道它是在開始而不是結束?如果輸入的書籍少於20本,該程序將與NPE崩潰,如果輸入了超過20本書籍,則會出現索引超出限制。 – dasblinkenlight 2013-02-22 01:18:44
告訴我們這是沒有意義的,有一個NPE w/o指示哪一行,什麼是空。如何加入一些printlns來檢查你對數據的假設或使用調試器? – 2013-02-22 01:19:03