Else If 条件语句的变量

Variable off an Else If Condition statement

我在下面的代码中有几个 else/if 语句。但是我想设置一个最终变量,它将根据用户输入设置最终的 if 语句。假设用户选择购买 6 "lathe"。应用的折扣将为 lathecost * 0.10。我想存储该变量,以便将来使用它。但是,如果用户选择 2 或 0,我不想创建单独的变量。我想让变量知道用户选择了什么,并根据 if/else 语句存储它。如果用户选择 2- 它将存储 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");
    }

无论是否有折扣,您都希望使用最终结果,因此无论是否有折扣,您都应该有一个变量。如果没有打折,直接将变量的值设置为原来的值即可。

事实上,我会稍微更改您的设计以存储打折的比例 - 因此 0 表示无折扣,0.05 表示 5% 等。然后您可以将 "compute discount" 与 "display discount" 分开部分:

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