我正在学习Java的入门课程,我正在建立一个小型图书馆系统,让图书管理员可以添加书籍,列出所有书籍并搜索特定书籍.
它现在正在运作,但在ArrayList一本书中只有标题.我想在图书馆中添加ISBN,作者,出版年份及其当前状态.如何在同一个中添加变量ArrayList?以下是我的ArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//Array form available books
public final class ListBook {
public static List<String> VALUES = new ArrayList<String>(Arrays.asList(
new String[] {"Book1","Book2","Book3","Book4"}
));
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,另一个重要的类允许图书馆员添加一本新书;
public class InsertBook {
// variables for the book info
public String name_book;
// Importing the list of books
ListBook lb = new ListBook();
// variable for the list of books
private int x;
// Constructors
Scanner input_name = new Scanner(System.in);
public void insertDataBook() {
System.out.println("----------------------------------------");
System.out.println("Write your book title:");
name_book = input_name.next();
System.out.println("----------------------------------------");
System.out.println("The following value was added");
System.out.println(name_book);
System.out.println("----------------------------------------");
lb.VALUES.add(name_book);
// To iterate through each element, generate a for so the array comes to
// a list. Through the variable x.
for (x = 0; x < lb.VALUES.size(); x++) {
System.out.println(lb.VALUES.get(x));
}
}
}
Run Code Online (Sandbox Code Playgroud)
应该怎么做?
而不是只有一个ArrayList只有你的标题的"字符串",你将需要一个ArrayList对象.考虑以下:
class Book {
public String ISBN;
public String author;
public String year;
public Book(String ISBN, String author, String year) {
this.ISBN = ISBN;
this.author = author;
this.year = year;
}
}
Run Code Online (Sandbox Code Playgroud)
然后您将添加到此列表,如下所示:
List<Book> VALUES = new ArrayList<Book>();
Book b = new Book("1234", "Name", "1984");
VALUES.add(b);
Run Code Online (Sandbox Code Playgroud)