Android JustJava应用calculatePrice方法计算逻辑错误排查求助
Hey there! Let's get that price calculation sorted out—your issue is a classic case of accidental double multiplication, plus a tiny typo in your topping checks. Here's what's going wrong and how to fix it:
The Root Cause of the Wrong Totals
Looking at your calculatePrice method, you're making two critical mistakes:
Double Multiplying by Quantity:
You first calculatebasePrice = quantity *5(which already accounts for the number of coffees), but then at the end you returnquantity * basePrice. That means you're squaring the quantity before multiplying by 5! For example:- Quantity = 2:
2*5 =10, then2*10=20(instead of the correct 10) - Quantity =3:
3*5=15, then3*15=45(instead of the correct15)
- Quantity = 2:
Incorrect Topping Check:
You usedaddChocolatefor both the whipped cream and chocolate topping checks. That means whipped cream never adds its $1 charge, and chocolate gets charged $3 (1+2) instead of just $2.
Corrected calculatePrice Method
Replace your existing calculatePrice method with this fixed version:
private int calculatePrice(boolean addWhippedCream, boolean addChocolate ) { // Price of 1 cup of coffee, multiplied by quantity int basePrice = quantity *5; // Add $1 per coffee if the user wants whipped cream if (addWhippedCream) { basePrice += 1 * quantity; } // Add $2 per coffee if the user wants chocolate if (addChocolate) { basePrice += 2 * quantity; } // Return the total price (no extra multiplication needed!) return basePrice; }
Note: I updated the topping charges to multiply by quantity—this ensures you charge for toppings per coffee, which makes sense for a coffee order. If you intended to charge a flat topping fee regardless of quantity, just remove the * quantity part from those lines.
Bonus: Small Polishing Fixes
While we're at it, here are a couple of minor tweaks for your creatOrderSummary method to make it cleaner:
- Change
TotalltoTotal(spelling error) - Capitalize "Add chocolate?" to match the whipped cream line
- Add a colon and space after
\nQuantityso it reads neatly:\nQuantity: " + quantity
Testing the Fix
After making these changes:
- Quantity 1 will return $5 (or $6 with whipped cream, $7 with chocolate, $8 with both)
- Quantity 2 will return $10 (or $12 with whipped cream, $14 with chocolate, $16 with both)
- Quantity3 will return $15 (as expected!)
That should resolve your calculation issues completely. Let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者Mostafa

