For my final CS180 project we have been given the task of creating a program that randomly generates some perishable and nonperishable items that would be found in a grocery cart and then printing a receipt for a customer.
The problem I am running into is finding a way to check the frequency of an item being created and preventing the item from printing multiple times on a receipt. For example, if someone buys 5 peaches the I want the output to be Peach $.99 X 5, total $4.95, instead of printing peach 5 times. Any suggestions?
The classes I have are Item (a super class of Perishable and Nonperishable), Perishable (creates perishable items) and nonperishable (nonperishable items and also figures their tax).
You could use a HashMap to store all items, mapping Item to quantity.
So something like
will be you receipt data structure.
And to to check if your
receipt
already has a particular item, sayi
, you would haveThis way you can avoid duplicates (all keys in HashMaps are unique).
You would of course have to implement the
equals
method in yourItem
class (for example, items are equal when their names are equal) to let the HashMap know when two Items are equal (because when it performs thecontains
check, it tests for equality using the object'sequals
method).