gpt4 book ai didi

java - 在 Java Arraylist 中存储用户输入

转载 作者:行者123 更新时间:2023-12-02 11:58:55 25 4
gpt4 key购买 nike

我正在尝试用 java 构建一个库类型程序,但在将用户输入存储在 ArrayList 中时遇到一些问题。我有一个名为“list”的ArrayList ' 存储 title , author , publisher , genre , yearpages我需要允许用户将书籍输入到 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("\n\n向图书馆添加一本新书:");

        list.add(new Book(title, author, publisher, genre, year, pages));
}

System.out.println("You have successfully added a new book to the library!");
}

最佳答案

您声明 list类型为ArrayList ,但您从未调用 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("\n\nAdd 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();
}
}

关于java - 在 Java Arraylist 中存储用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47401448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com