如何在"Sales Report File"中展示所有已订购商品?附现有代码
First, let's fix an immediate bug in your switch statement—you’re missing a break after the "Cookies" case, which would cause the code to fall through to the "Sales Report File" case every time someone buys cookies. Then, we’ll add a way to track the quantity of each product sold, and use that to build your sales report correctly.
Step 1: Add a Sales Tracking Map
We’ll use a HashMap to keep count of how many times each product has been ordered. Add this as a class-level variable:
private final Map<String, Integer> salesCount = new HashMap<>();
Step 2: Update Sales Count When Selling Products
Modify each product case in your actionPerformed method to update the map only when a sale is successful. For example, for Candy:
case "Candy": if (sellProduct(candy, "Candy")) { // Assuming sellProduct returns true if the sale worked salesCount.put("Candy", salesCount.getOrDefault("Candy", 0) + 1); } break;
(Note: I added a check for successful sales—adjust this based on whether your sellProduct method returns a boolean. If it doesn’t, you can skip the check, but it’s better to only count valid sales.)
Step 3: Generate the Sales Report String
When the "Sales Report File" button is clicked, build a dynamic string that lists each product and its quantity:
case "Sales Report File": StringBuilder report = new StringBuilder("Items Sold:\n"); for (Map.Entry<String, Integer> entry : salesCount.entrySet()) { report.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } // Add a message if no items were sold if (salesCount.isEmpty()) { report.append("No items have been sold yet."); } JOptionPane.showMessageDialog(null, report.toString(), "Sales Report ~ ", JOptionPane.PLAIN_MESSAGE); break;
Full Modified Code
Here’s the updated version of your class with all these changes:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.JOptionPane; // Assume Dispenser class is defined elsewhere class Dispenser { private int count; private int price; public Dispenser(int count, int price) { this.count = count; this.price = price; } // Example sell method—adjust to match your actual implementation public boolean sell() { if (count > 0) { count--; return true; } return false; } } public class VendingMachine { private final Dispenser candy = new Dispenser(100, 50); private final Dispenser chips = new Dispenser(100, 65); private final Dispenser gum = new Dispenser(75, 45); private final Dispenser cookies = new Dispenser(100, 85); private final JButton candyB; private final JButton chipsB; private final JButton gumB; private final JButton cookiesB; private final Map<String, Integer> salesCount = new HashMap<>(); // Constructor to initialize buttons public VendingMachine() { candyB = new JButton("Candy"); chipsB = new JButton("Chips"); gumB = new JButton("Gum"); cookiesB = new JButton("Cookies"); // Attach listeners to buttons candyB.addActionListener(new ButtonHandler()); chipsB.addActionListener(new ButtonHandler()); gumB.addActionListener(new ButtonHandler()); cookiesB.addActionListener(new ButtonHandler()); } // Updated sellProduct method to return success status private boolean sellProduct(Dispenser dispenser, String productName) { boolean success = dispenser.sell(); if (success) { JOptionPane.showMessageDialog(null, "Sold " + productName, "Success", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, productName + " is out of stock!", "Error", JOptionPane.ERROR_MESSAGE); } return success; } private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "Exit": System.exit(0); break; case "Candy": if (sellProduct(candy, "Candy")) { salesCount.put("Candy", salesCount.getOrDefault("Candy", 0) + 1); } break; case "Chips": if (sellProduct(chips, "Chips")) { salesCount.put("Chips", salesCount.getOrDefault("Chips", 0) + 1); } break; case "Gum": if (sellProduct(gum, "Gum")) { salesCount.put("Gum", salesCount.getOrDefault("Gum", 0) + 1); } break; case "Cookies": if (sellProduct(cookies, "Cookies")) { salesCount.put("Cookies", salesCount.getOrDefault("Cookies", 0) + 1); } break; // Fixed missing break! case "Sales Report File": StringBuilder report = new StringBuilder("Items Sold:\n"); for (Map.Entry<String, Integer> entry : salesCount.entrySet()) { report.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } if (salesCount.isEmpty()) { report.append("No items have been sold yet."); } JOptionPane.showMessageDialog(null, report.toString(), "Sales Report ~ ", JOptionPane.PLAIN_MESSAGE); break; default: break; } } } }
Key Notes:
- Sales Tracking: The
HashMapkeeps track of how many times each product was successfully sold—so if someone buys 2 cookies, it will show "Cookies: 2" in the report. - Fixed Fallthrough: Added the missing
breakin the "Cookies" case to prevent accidental triggering of the sales report. - Dynamic Report: The report builds itself based on actual sales data, so it will only show products that have been ordered.
- Success Check: We only increment the sales count if the product was available and sold successfully.
内容的提问来源于stack exchange,提问作者Xen

