You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android JustJava应用calculatePrice方法计算逻辑错误排查求助

Fixing the Price Calculation Bug in Your JustJava App

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:

  1. Double Multiplying by Quantity:
    You first calculate basePrice = quantity *5 (which already accounts for the number of coffees), but then at the end you return quantity * basePrice. That means you're squaring the quantity before multiplying by 5! For example:

    • Quantity = 2: 2*5 =10, then 2*10=20 (instead of the correct 10)
    • Quantity =3: 3*5=15, then 3*15=45 (instead of the correct15)
  2. Incorrect Topping Check:
    You used addChocolate for 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 Totall to Total (spelling error)
  • Capitalize "Add chocolate?" to match the whipped cream line
  • Add a colon and space after \nQuantity so 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:17:04