TheGamer27
TheGamer27

Reputation: 25

How would I add a object to a arraylist using scanner?

I have an arraylist and my goal is to keep adding to an object to the arraylist until the user types in a value. I have two different classes. I have tried to use scanner but that only changes the name of the variable and doesn't create a new object. Would I have to inherit from the other class. How would I keep increasing the size of the arraylist? Any help is appreciated.

Below is my first class:

public class Real_Entertainment 
{
    String BookName; 
    String Author; 
    double Rating; 
    int Purchases;

    public Real_Entertainment(String BookName, String Author, double Rating, int Purchases, int i)
    {
        this.BookName = BookName;
        this.Author = Author;
        this.Rating = Rating;
        this.Purchases = Purchases;
    }
    public void setBookName(String BookName)
    {
        this.BookName = BookName;
    }
    public void setAuthor (String Author )
    {
        this.Author = Author;
    }
    public void setRating (double Rating)
    {
        this.Rating = Rating;
    }
    public void setPurchased (int Purchases)
    {
        this.Purchases = Purchases;
    }

}

Below is my main class:

import java.util.Scanner;
import java.util.ArrayList;

public class Real_Main 
{
    public static void main(String[] args) 
    {
        ArrayList<Real_Entertainment> print = new ArrayList<Real_Entertainment>();
        Real_Entertainment Book1 = new Real_Entertainment("The Nickel Boys ", "Colson 
        Whitehead", 4.3, 500,000);
        Real_Entertainment Book2 = new Real_Entertainment("Olive, Again", "Elizabeth Strout", 6, 
        321,000);
        Real_Entertainment Book3 = new Real_Entertainment("Gingerbread", "Helen Oyeyemi", 2, 
        681,000);
        Real_Entertainment Book4 = new Real_Entertainment ("On Earth We're Briefly Gorgeous", 
        "Ocean Vuong", 2, 421,000);

        print.add(Book1);
        print.add(Book2);
        print.add(Book3);
        print.add(Book4);
    }

    public void addToList(ArrayList<Real_Entertainment> print)
    { 

         //The method where it adds to the arraylist    
    }

}

Upvotes: 0

Views: 342

Answers (1)

Bill Horvath
Bill Horvath

Reputation: 1717

What you want to do, conceptually, is capture in the input from the user (e.g., the name of the book), then use that data to instantiate a new Real_Entertainment instance (if that's all you need), then add the new instance to your existing list. For example:

Scanner scanner = new Scanner(System.in);
System.out.print("What is your book's title? ");
String title = scanner.next();
Real_Entertainment realEntertainment = new Real_Entertainment(title, null, 0, 0, 0);
print.add(realEntertainment);

Upvotes: 1

Related Questions