Preventing multiple objects from being printed

我只是一个虾纸丫 提交于 2019-12-25 05:06:54

问题


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).


回答1:


You could use a HashMap to store all items, mapping Item to quantity.

So something like

HashMap<Item,Integer> receipt = new HashMap<Item,Integer>();

will be you receipt data structure.

And to to check if your receipt already has a particular item, say i, you would have

if (receipt.containsKey(i){
    receipt.get(i) += 1; // increment qantity
    // do other stuff to total, taxes etc.
} else { // this is the first time this kind of item is being added
    receipt.put(i, new Integer(1)); // so put it in the map
}

This way you can avoid duplicates (all keys in HashMaps are unique).

You would of course have to implement the equals method in your Item 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 the contains check, it tests for equality using the object's equals method).



来源:https://stackoverflow.com/questions/20084251/preventing-multiple-objects-from-being-printed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!