一个数组中有多个变量?

时间:2015-03-22 15:16:40

标签: java arraylist

我正在学习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"} 
    ));
}

在这种情况下,另一个重要的类允许图书管理员添加新书;

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));
        }

    }

}

应该怎么做?

2 个答案:

答案 0 :(得分:6)

您可能希望拥有一个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);

答案 1 :(得分:2)

您必须制作一个包含成员变量ISBN,年份,标题等的Book类

然后你可以像这样制作一个Book对象的ArrayList:ArrayList<Book> bookList = new ArrayList<Book>();

Book类看起来如下所示:

public class Book{

    String ISBN;
    int year:

    Book(String ISBN, String year){
        this.ISBN = ISBN;
        this.year = year;

    void setISBN(String ISBN)
    {
        this.ISBN = ISBN;
    }

    String getISBN()
    {
        return ISBN;
    }

    void setYear(int year)
    {
        this.year = year;
    }

    int getYear()
    {
        return year;
    }

}

然后,您可以将Book对象添加到Book对象的ArrayList中,如下所示:

ArrayList<Book> bookList = new ArrayList<Book>();
Book aBook = new Book("335-0424587965", 2001);
bookList.add(aBook);