我正在学习 Java 入门类(class),其中我正在构建一个小型图书馆系统,图书馆员可以通过该系统添加书籍、列出所有书籍并搜索特定书籍。
它现在可以工作,但是在一本书的 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"}
));
}
本例中的另一个重要类允许图书管理员添加一本新书;
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));
}
}
}
应该怎样做?
最佳答案
您不希望拥有一个仅包含标题的“字符串”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;
}
}
然后您可以按如下方式添加到此列表:
List<Book> VALUES = new ArrayList<Book>();
Book b = new Book("1234", "Name", "1984");
VALUES.add(b);
关于java - 一个数组中有多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196042/