将用户输入存储在 Arraylist Java 中



我正在尝试用java构建一个库类型程序,但是在将用户输入存储在ArrayList中时遇到了一些麻烦。我有一个名为"list"的ArrayList,它存储书籍的titleauthorpublishergenreyearpages,我需要允许用户将书籍输入到ArrayList中,以便以后能够查看存储在ArrayList中的所有书籍。

当我运行程序时,它会抛出此错误:

Exception in thread "main" java.lang.NullPointerException
at thelibrary.addBooks(Book.java:73)
at Menu.bookmenu(Menu.java:68)
at Menu.main(Menu.java:27) 

我哪里出错了?

public static void addBooks() {
Scanner newBooks = new Scanner(System.in);
ArrayList<Book> list = null;
for (int i = 0; i < 1; i++) {

System.out.println("\将新书添加到库:");

list.add(new Book(title, author, publisher, genre, year, pages));
}
System.out.println("You have successfully added a new book to the library!");
}

你声明listArrayList类型,但你从未调用过 ArrayList 构造函数(你把它设置为等于null,而是)。

而不是:ArrayList<Book> list = null;

使用ArrayList<Book> list = new ArrayList<Book>();.

此外,list在离开addBooks()范围时会死亡。试试这个,改为:

class thelibrary {
public static ArrayList<Book> list = new ArrayList<Book>();
public static void allBooks() {
Book obj1 = new Book("Harry Potter and the Philosopher's Stone","JK Rowling","Bloomsbury","Genre",1997,223);
Book obj2 = new Book("Alexander Hamilton","Ron Chernow","Head of Zeus","Biograophy",2016,818);
Book obj3 = new Book("To Kill a Mockingbird","Harper Lee","Arrow","Southern Gothic",1960,309);
list.add(obj1);
list.add(obj2);
list.add(obj3);
for(Book ob : list) {
System.out.println("Title: " + ob.title);
System.out.println("Author: " + ob.author);
System.out.println("Publisher: " + ob.publisher);
System.out.println("Genre: " + ob.genre);
System.out.println("Year: " + ob.year);
System.out.println("Pages: " + ob.pages);
System.out.println(" - - - - - - - - - - - - - - - - - - - - - - - - ");
}
Menu.bookmenu();
}
public static void addBooks() {
Scanner newBooks = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
System.out.println("nnAdd a new book to the library:");
System.out.println("n>Please enter book title: ");
String title = newBooks.nextLine();
System.out.println(">Please enter book author: ");
String author = newBooks.nextLine();
System.out.println(">Please enter book publisher: ");
String publisher = newBooks.nextLine();
System.out.println(">Please enter book genre: ");
String genre = newBooks.nextLine();
System.out.println(">Please enter book release year: ");
int year = newBooks.nextInt();
System.out.println(">Please enter number of book pages: ");
int pages = newBooks.nextInt();
list.add(new Book(title, author, publisher, genre, year, pages));
System.out.println("You have successfully added a new book to the library!");
Menu.bookmenu();   
}
}

相关内容

  • 没有找到相关文章

最新更新