簡體   English   中英

在其他If條件語句中可變

[英]Variable off an Else If Condition statement

我下面的代碼中有幾個else / if語句。 但是我想設置一個最終變量,該變量將根據用戶輸入設置最終的if語句。 假設用戶選擇購買6台“車床”。 應用的折扣為車床成本* 0.10。 我想存儲該變量,以便將來使用。 但是,如果用戶選擇2或0,我不想創建單獨的變量。我想讓變量知道用戶選擇了什么,並取決於if / else語句將其存儲。 如果用戶選擇2-itll存儲lathecost的最終成本* 0.05,如果用戶選擇10 itll存儲lathecost的最終成本* 0.10,依此類推。 我該如何實現?

  double numlathe;

    numlathe = input.nextFloat();
    final double priceoflathe = 20000;
    double lathecost = priceoflathe * numlathe;


    if (numlathe<0) {
        System.out.println("No discount applicable for 0 number of lathe purchase");
    }
    else if(numlathe<2) {
        System.out.println("Discount of lathe matchine purchase = 0 ");
    }

    else if(numlathe<5){
        System.out.println("There is discount that can be applied");

        System.out.println("Total cost so far is" + lathecost * 0.05 + " dollars");
    }

    else if(numlathe>=5){
        System.out.println("There is discount that can be applied.");

        System.out.println("Total cost so far with discount is "  +  lathecost * 0.10 + " dollars");
    }

無論是否有折扣,您都希望使用最終結果,因此無論是否有折扣,都應該為其使用變量。 如果沒有折扣,只需將變量的值設置為原始值即可。

實際上,我會略微更改您的設計以存儲折后的比例-因此0表示無折扣,0.05表示5%等。然后,您可以將“計算折扣”與“顯示折扣”部分分開:

private static final BigDecimal SMALL_DISCOUNT = new BigDecimal("0.05");
private static final BigDecimal LARGE_DISCOUNT = new BigDecimal("0.10");
private static BigDecimal getDiscountProportion(int quantity) {
    if (quantity < 0) {
        throw new IllegalArgumentException("Cannot purchase negative quantities");
    }
    return quantity < 2 ? BigDecimal.ZERO
        : quantity < 5 ? SMALL_DISCOUNT
        : LARGE_DISCOUNT;
}

然后:

int quantity = ...; // Wherever you get this from
BigDecimal discountProportion = getDiscountProportion(quantity);
BigDecimal originalPrice = new BigDecimal(quantity).multiply(new BigDecimal(20000));
BigDecimal discount = originalPrice.multiply(discountProportion);
// TODO: Rounding
if (discount.equals(BigDecimal.ZERO)) {
    System.out.println("No discount applied");
} else {
    System.out.println("Discount: " + discount);
}
BigDecimal finalCost = originalPrice.subtract(discount);

請注意,此處使用BigDecimal而不是double - double通常不適合貨幣值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM