McKeene McKeene - 5 months ago 10
Java Question

Multiple variables in one array?

I am taking an introduction course to Java, where I am building a small library systems that lets a librarian add books, list all the books and search for a specific book.

It is working for now, but in the

ArrayList
of a book there is only the title. I would like to add ISBN, author, year published and its current status in the library. How do I add the variables in the same
ArrayList
?
Below is my
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"}
));
}


The other important class in this case allows the librarian to add a new book;

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

}

}


How should it be done?

Answer

Instead of having an ArrayList of "Strings" which have only your title, you will want to have an ArrayList of objects instead. Consider the following:

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

Then later you would add to this list as follows:

List<Book> VALUES = new ArrayList<Book>();
Book b = new Book("1234", "Name", "1984");
VALUES.add(b);
Comments