Here's the code for the separate class Product which the ArrayList is based on. The chapter has us learning ArrayList, Loops, and Iterator so anything more advanced than that has not been covered and is not meant to be used to complete the exercise.
public class Product
{
// An identifying number for this product.
private int id;
// The name of this product.
private String name;
// The quantity of this product in stock.
private int quantity;
/**
* Constructor for objects of class Product.
* The initial stock quantity is zero.
* @param id The product's identifying number.
* @param name The product's name.
*/
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}
/**
* @return The product's id.
*/
public int getID()
{
return id;
}
/**
* @return The product's name.
*/
public String getName()
{
return name;
}
/**
* @return The quantity in stock.
*/
public int getQuantity()
{
return quantity;
}
/**
* @return The id, name and quantity in stock.
*/
public String toString()
{
return id + ": " +
name +
" stock level: " + quantity;
}
public class StockManager
{
// A list of the products.
private ArrayList<Product> stock;
/**
* Initialise the stock manager.
*/
public StockManager()
{
stock = new ArrayList<>();
}
/**
* Add a product to the list.
* @param item The item to be added.
*/
public void addProduct(Product item)
{
stock.add(item);
}
How the project is set up is I create a StockManager object and a few Product objects (Entering parameters for ProductID and ProductName) when the object is created. I then can call the default addProduct method to add those newly created Product objects to the ArrayList. What I am tasked with is modifying the addProduct method so that a new product won't be added to the list if a product with the same ID was already entered into the list.
At first, I thought I was maybe supposed to use the "for each" loop and do something like the following:
public void addProduct(Product item)
{
for(Product product : stock){
if(product.getID()!=item.getID())
stock.add(item);
}
But this fails to add anything to the list. If I add a product object to the list with this method and then call a method to print/find the product it just returns null and shows nothing was entered.
I then thought maybe I'm supposed to do something like
public void addProduct(Product item)
{
if(!stock.contains(item.getID()))
stock.add(item);
But this doesn't work either. My Professor hinted that I should be using the null value, but I messed around with null and it never works, because getID is an integer, and even if I got it working I feel like I'm not setting the problem up right.