变量Else If Condition语句

时间:2016-02-25 06:44:27

标签: java eclipse if-statement double

我的代码中有几个else / if语句。但是我想设置一个最终变量,它将根据用户输入设置最终的if语句。让我们说用户选择购买6“车床”。应用的折扣将为lathecost * 0.10。我想存储该变量,以便将来可以使用它。但是,如果用户选择2或0,我不想创建一个单独的变量。我希望变量知道用户选择了什么,并根据if / else语句存储它的内容。如果用户选择2- itll存储lathecost的最终成本* 0.05,如果用户选择10,则存储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");
    }

1 个答案:

答案 0 :(得分:2)

您是否希望使用最终结果是否有折扣,因此您应该有一个变量,无论是否有折扣。如果没有折扣,只需将变量的值设置为原始值。

事实上,我会稍微改变你的设计以存储打折的比例 - 所以0表示无折扣,0.05表示5%等。然后你可以分开&#34;计算折扣&#34;来自&#34;显示折扣&#34;部分:

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通常不适用于货币值。