How would I go about only inserting an item if the item does not have the same name as the other items in the arraylist within my insertUniqueItem() method?
public void insertUniqueItem() { } public static void main(String[] args) { ShoppingCart sc = new ShoppingCart(); Item a = new Item("Kraft Cheese", 4, ""Best Cheese in Town!""); Item b = new Item("Bottle of Water", 2.50, ""Refreshing Water!""); sc.insertItem(a); sc.insertItem(b); sc.printInvoice(); sc.insertUniqueItem(); sc.print(); DecimalFormat df = new DecimalFormat("#.00"); System.out.println("Total Price: $" + df.format(sc.getTotal())); } }
Advertisement
Answer
You need to check if an item with the same name already exists in your list:
public void insertUniqueItem(Item item) { if(!contains(item)) { cart.add(item); } } private boolean contains(Item item) { for(Item i : cart) { if(i.getName().equals(item.getName())) { return true; } } return false; }