当我尝试运行以下代码块时,我得到Null Pointer Exceptions,该代码块应该打印出存储在txt文件中的书籍列表。 (在解析之前首先具有书籍对象的“环形交叉口”实现是有目的的)
Null Pointer异常的出现在代码中指出(基本上是引用BookPrint的任何地方)
有什么想法吗?
import java.io.*;
import java.util.Scanner;
/** there is a basic Book.java file that stores a title and a category that are set by a *constructor and has get methods for each and a "toString" Method for a Book object that *prints out the book's title and category
**/
/**
** BookPrint prints out all the books in the txt file as stored in an array of book objects
**derived by parsing the text file
**/
public class BookPrint
{
private Book[] b_books;
private Scanner defaultFR;
private Book bookPerLine;
/**
* main takes a txt file with book titles on separate lines in title category format like "The Lion King, Children"/n "Yellow Sun, Fiction" /n etc
*/
public static void main(String[] argv)
throws FileNotFoundException
{
BookPrint bk;
/**
The following declaration gives a NullPointer exception
**/
bk = new BookPrint(new FileReader("C:\\Users\\Owner\\workspace\\Book\\src\\hotBooks.txt"));
Book[] books;
books = bk.getBooks();
//
//take each book in and print out
for(int i =0; i<50; i++){
books[i].toString();
}
}
/** constructor populates BookPrint
*
*/
public BookPrint(FileReader fr)
throws ParseError
{
defaultFR = new Scanner(fr);
//Null pointer exception when the parseAll method is called
this.parseAll(defaultFR);
}
/** Return array of books
*/
public Book[] getBooks()
{
return b_books;
}
/** Parse all.
*Null Pointer Exception here as well
*
*/
private void parseAll(Scanner scn)
throws ParseError
{
//open scanner object that reads file
//for all books in array, if there is next line parseOne, and store in book array
try{
while(scn.hasNext()){
for(int i=0; i< 50; i++){
b_books[i]= parseOne(scn.nextLine());
}
}
}
finally{
scn.close();
}
}
/** Parse one
*
*
*/
private Book parseOne(String line)
throws ParseError
{
Scanner scn = new Scanner(line);
//parse line by "," , store each value as book.title and book.category and return book
scn.useDelimiter(",");
if (scn.hasNext() ){
String title = scn.next();
String category = scn.next();
bookPerLine = new Book(title, category);
}
else {
System.out.println("Empty or invalid line. Unable to process.");
}
scn.close();
return bookPerLine;
}
}
答案 0 :(得分:8)
您在b_books[i]
中分配parseAll()
而未创建数组。
private Book[] b_books = new Book[50];