防止打印多个对象 [英] Preventing multiple objects from being printed

查看:78
本文介绍了防止打印多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的最终CS180项目,我们的任务是创建一个程序,该程序随机生成一些易腐烂和不易腐烂的物品,这些物品会在杂货店的购物车中找到,然后为客户打印收据.

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.

我遇到的问题是找到一种检查创建项目的频率并防止该项目在收据上多次打印的方法.例如,如果某人买了5个桃子,我希望输出为Peach $ .99 X 5,总计$ 4.95,而不是打印桃子5次.有什么建议吗?

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?

我所拥有的类别是Item(易腐烂和不易腐烂的超类),易腐烂(创建易腐烂的物品)和不易腐烂(不易腐烂的物品,还要计算税额).

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.

类似

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

将是您的收据数据结构.

will be you receipt data structure.

要检查您的receipt是否已经有特定的商品,例如i,您应该拥有

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
}

这样,您可以避免重复(HashMap中的所有键都是唯一的).

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

您当然必须在Item类中实现equals方法(例如,当项目名称相等时,项目相等),以让HashMap知道何时两个Item相等(因为它在执行contains检查,它使用对象的equals方法测试是否相等.

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

这篇关于防止打印多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆