我正在嘗試創建代碼來獲取客戶購買的商品數量,然后列印出將打折的數量。
1-3 items purchased will get no discount
4-6 items purchased will get 5% discount
7-10 items purchased will get 10% discount
11 or more items purchased will get a 15% discount
任何幫助將不勝感激,謝謝。這是我創建的代碼。
package discount;
import java.util.Scanner;
public class Discount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input the number of items: ");
int quantity = input.nextInt();
int[] discount = {0, 5, 10, 15};
if (quantity >= 1 && quantity < 4) {
System.out.print("no discount");
} else if (quantity >= 4 && quantity < 7) {
System.out.print(discount[1] "% discount");
} else if (quantity >= 7 && quantity < 11) {
System.out.print(discount[2] "% discount");
} else if (quantity >= 11) {
System.out.print(discount[3] "% discount");
}
}
}
uj5u.com熱心網友回復:
我建議您通過將負責計算折扣和列印訊息的代碼提取到單獨的方法中來應用分解。即使沒有 switch 運算式,它也會使您的代碼更清晰。
1.計算折扣:
public static int getDiscount(int items) {
return switch(items) {
case 0, 1, 2, 3 -> 0;
case 4, 5, 6 -> 5;
case 7, 8, 9, 10 -> 10;
default -> 15;
};
}
2. 列印訊息:
public static void printMessage(int discount) {
switch(discount) {
case 0 -> System.out.print("no discount");
default -> System.out.println(discount "% discount");
}
}
3.主要:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input the number of items: ");
printMessage(getDiscount(input.nextInt()));
}
- 此代碼將適用于 Java 14 及更高版本
uj5u.com熱心網友回復:
如果沒有 Kotlin when,Javaswitch可能會也可能不會做任何你想做的事情。但是如果你確實想用 寫if-else,它可以清理:
if(quantity > 0){
int discount = -1
if(quantity < 4) discount = 0;
else if (quantity < 7) discount = 5;
else if (quantity < 11) discount = 10;
else discount = 15;
printDiscountMessage(discount)
}
uj5u.com熱心網友回復:
用這個
int discountCalculation = (quantity >= 1 && quantity < 4) ?discount[0]: (quantity >= 4 && quantity < 7)?discount[1]: (quantity >= 7 && quantity < 11) ?discount[2]:discount[3];
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/417517.html
標籤:
