【发布时间】:2022-01-19 02:22:05
【问题描述】:
我正在尝试创建代码来获取客户购买的商品数量,然后打印出将打折的数量。
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");
}
}
}
【问题讨论】:
-
在这种情况下,switch 语句会起作用。见docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html。如果要枚举的案例标签太多,那么
TreeMap类是一个替代方案。 -
我同意上面的说法,但上面的代码还不是我归类为“冗长”的代码。格式不正确,但我可以为您解决。
-
同意。值得怀疑的是是否值得努力缩短这段代码。
-
感谢您的评论!你能教我如何使它格式化吗?
-
一种简化方法是删除
discount数组,并在 if 语句的主体中使用文字。这样做的好处是您可以立即看到与哪个折扣相关联的数量,并消除了在 if 语句中存在数组索引的可能性,而该索引在discount中不存在。但是,此更改与学习 Java 的目标相冲突,我希望您在处理此代码时确实获得并修复了至少一个ArrayIndexOutOfBoundsException!
标签: java arrays if-statement range