Reputation: 139
I have a product with following format:
public Item(String barcode, double price, int inStock) {
if (barcode == null) {
barcode = "";
}
if (price < 0) {
price = 0;
}
if (inStock < 0) {
inStock = 0;
}
this.barcode = barcode;
this.price = price;
this.inStock = inStock;
}
And an ArrayList
to store the items in another class:
public class Inventory {
private ArrayList<Item> currentInventory;
public Inventory() {
this.currentInventory = new ArrayList<Inventory>();
}
/**
* Adds default products to the inventory
*/
public void inventoryDefault() {
this.currentInventory("JMS343", 100.00, 5);
this.currentInventory("RQ090", 50.00, 20);
}
I cannot figure out how to add 2 items as defaults, or always in the currentInventory
, until removed by the user. I have also tried:
public void inventoryDefault() {
this.currentInventory.add(JMS343, 100.00, 5);
this.currentInventory.add(RQ090, 50.00, 20);
}
This, however, shows an error that JMS343
and RQ090
cannot be resolved to variables. I thought I was creating them at this point, since it is just a String. Any help would be great. Thanks!
Working solution as shown below:
public void inventoryDefault() {
this.currentInventory.add(new Item("JMS343", 100.00, 5));
this.currentInventory.add(new Item("RQ090", 50.00, 20));
}
Upvotes: 2
Views: 2378
Reputation: 22244
You need to construct Item
objects with the constructor to add them to the ArrayList
. E.g.
public void inventoryDefault() {
currentInventory.add(new Item("JMS343", 100.00, 5);
currentInventory.add(new Item("RQ090", 50.00, 20);
}
Or add an appropriate function to Inventory
that may also be useful otherwise :
public void addItem(String barcode, double price, int inStock) {
Item item = new Item(barcode, price, inStock);
currentInventory.add(item);
}
public void inventoryDefault() {
addItem("JMS343", 100.00, 5);
addItem("RQ090", 50.00, 20);
}
Upvotes: 2
Reputation: 6082
do this to the constructor of the Inventory
class
public Inventory() {
this.currentInventory = new ArrayList<Inventory>();
this.currentInventory.add(new Item("JMS343", 100.00, 5));
this.currentInventory.add(new Item("RQ090", 50.00, 20);
}
Upvotes: 2