Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid. The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Look, normally I wouldn't post a working example, but it looks like you put enough effort into this, and I think that a full example with an explanation might be helpful. If the moderators think otherwise, I'm sure they will edit my post.
Most of the logic of the problem is in this one class, Item. All you need now is a class Invoice which simply maintains a list (hint: ArrayList) of orders, each order containing the Item, the quantity of the item, and whether it's imported. Note the following:
- This setup eliminates a lot of your classes. You don't really need a decorator pattern to calculate the taxes, it is much more simple and readable to let the Item calculate its own tax.
- The Item class is immutable. Always strive to make your classes immutable, unless it's impractical to do so. Note how all members are final, as well as the class itself.
- Visibility is reduced where possible. Think long and hard before you use public or protected access modifiers. If you don't need them, don't use them.
- Category is an enum. Always prefer enums over a collection of constants.
- Tax is calculated on the fly. It isn't added as a member variable of the Order or Item, because it can dynamically be calculated from the members in Item.
- Normally I would also include equals and hashCode methods, but for brevity I left them out.
Please tell me whether you understand why this code is 'better'. If someone thinks this code is worse, please tell me, so I can learn about your ideas as well.
A wop bop a lu bob a womp bam boom. Tutti frutti ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop