繁体   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