Jump to content

Help with Java, how to add to an arraylist from a class

Hello, I had to create a class that acts as a cash register, now I just need to figure out how to add items to the array list.

 

My assignment says, " Create a main application which creates a CashRegister object, adds several items to the object, then tests all of its methods. "

 

If someone could get me started I would greatly appreciate it. I mainly don't know how to reference the array. I named the arraylist items but this.items is not working.

I will attach the class file and the file with main.

 

CashRegister.java is the class file and L04P8_16.java is the file that has main, which will test the CashRegister class.

 

Thank you.

L04P8_16.java

CashRegister.java

Link to post
Share on other sites

First

register.addItem(this.items());

is wrong : the method addItem can only add 1 item, and not an arrayList
Plus, this.items is a variable, so no ()

If you want to add some items to your register object, you need to create the items first with something like that

double item1 = 1.1;
double item2 = 2.2;

To add those to register 

register.addItem(item1);
register.addItem(item2);

 

Gaming rig : i5 6600k | EVGA 1070 FTW | 16Go DDR4 HyperX Fury | Intel 600p - WD Black

Laptop : Macbook 2017

Home server : AMD A10 7700k | 2*2TB unraid array + 250GB ssd cache

Link to post
Share on other sites

If it's the main class create a constructor that allows you to use the main class.

 

Example:

MainClassName m;

 

public ClassYouAreAccessingFrom(MainClassName main) {

this.m = main;

}

 

Then use this:

 

m.ArrayListName.add(string);

 

In the main class or whatever class that creates this class do this:

new ClassYouAreAccessingFrom(m);

 

If you don't understand what I am saying, pm me and I'll explain it better. 

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×