Java中processPurchase方法是否正确扣减客户账户金额?
Here are the most likely causes for your total sales overcount and unexpected negative account issues, along with actionable checks:
Common Root Causes & Fixes
Incorrect discount application for specialized customers
If Student/Staff customers are supposed to get discounted deductions but your code uses the full price instead, total sales will be inflated, and accounts may be over-deducted into negatives. Verify that subclass-specific logic (e.g.,account -= price * 0.8for students) is properly implemented and being called instead of the generic Customer deduction.Missing balance validation before deduction
If you’re processing purchases without checking if the customer has enough balance first, you’ll end up with more negative accounts than intended. Additionally, if total sales are incremented even for failed/overdrawn purchases, that will skew your sales numbers. Add checks likeif (account >= calculatedDeduction)before applying the deduction, and only update total sales when the transaction is valid.Polymorphism misimplementation
If yourprocessPurchasemethod isn’t leveraging polymorphism correctly (e.g., treating all customers as genericCustomerinstead of their specific subclass), the wrong deduction logic will run. Ensure that the deduction method (e.g.,deductForPurchase()) is declared as abstract in the parentCustomerclass and overridden properly inStudentCustomerandStaffCustomer.Total sales calculation uses pre-discount price
If you’re adding the original item price to total sales instead of the actual deducted amount (e.g., adding $100 for a student’s $80 discounted purchase), your total sales will be artificially high. Double-check that total sales are updated with the exact amount taken from the customer’s account.Unenforced negative balance rules
If certain customer types shouldn’t be allowed to have negative accounts (e.g., students), but your code doesn’t restrict this, the negative account count will be off. Confirm that your logic enforces type-specific balance limits (e.g., block purchases for students if balance is insufficient).
Debugging Steps
- Add logging to each deduction method: print customer type, initial balance, purchase amount, deducted amount, and final balance for every transaction. This will let you spot mismatches immediately.
- Run a controlled test with known values:
- Student with $100 balance buying a $50 item (should deduct $40, balance $60, sales +$40)
- Staff with $30 balance buying a $50 item (if negatives are allowed: balance -$20, sales +$50)
- Generic customer with $40 balance buying a $50 item (transaction should fail, balance unchanged, sales unaffected)
- Use a debugger to step through
processPurchaseand confirm that the correct subclass deduction logic is being executed for each customer type.
内容的提问来源于stack exchange,提问作者adriany2kx

