java - 商品数量折扣
问题描述
import java.util.Scanner;
public class ItemDiscount {
public static void main(String[] args) {
int a = 0;
int b = 5;
final int DISCOUNT1 = 1-12;
final int DISCOUNT2 = 13-49;
final int DISCOUNT3 = 50-99;
final int DISCOUNT4 = 100-199;
final int DISCOUNT5 = 200;
int [] Purchased_Item = {DISCOUNT1, DISCOUNT2, DISCOUNT3, DISCOUNT4, DISCOUNT5};
double [] Discount = {0.00, 0.10, 0.14, 0.18, 0.20};
double ItemDiscount = 0;
int Item1 = 0;
boolean Item = false;
Scanner input = new Scanner (System.in);
System.out.println("Enter the number of item/s you purchased: ");
int num_of_item = input.nextInt();
for (int x = 0; x < b; x++){
if (Item1 == Purchased_Item[x]){
Item = true;
ItemDiscount = Discount[x];
}
}
if (Item)
System.out.println("No Discount");
else
System.out.println("The discount of " + num_of_item +" items is " + ItemDiscount);
}
}
这是我一直在处理的代码。您插入您将购买的商品数量,如果您有折扣,系统应该给出输出。
这是一个允许用户输入商品数量并检查折扣的程序。
这是指导表
当我输入任何数字时,我得到的输出一直给我 0.0 或 0% 的折扣。认为应该说当你输入200及以上时,你应该有0.20或20%的折扣。
请给我建议并教我应该做什么。谢谢
解决方案
我个人会选择一个不同的数据结构来保存折扣级别 - 例如 a LinkedHashMap
,用外行的话来说是 a HashMap
,它保持您创建它的顺序。分开存储 2 组值,即使它们明显相互关联也不是一个好主意。然后创建一个方法,根据购买的商品数量返回正确的折扣级别。让我们称这个类Discount.class
:
import java.util.LinkedHashMap;
import java.util.Map;
public class Discount {
private Map<Integer, Double> discountMap;
public Discount() {
discountMap = new LinkedHashMap<Integer, Double>();
discountMap.put(0, 0.00d);
discountMap.put(12, 0.10d);
discountMap.put(49, 0.14d);
discountMap.put(99, 0.18d);
discountMap.put(199, 0.20d);
}
public Double getDiscountAmount(int amountPurchased) {
Double currentDiscount = 0.00d;
for (Map.Entry<Integer, Double> entry : discountMap.entrySet()) {
if (amountPurchased > entry.getKey()) {
currentDiscount = entry.getValue();
} else {
return currentDiscount;
}
}
return currentDiscount;
}
}
然后你可以在你的程序中使用这个类来获得你应该申请的折扣级别
Scanner input = new Scanner (System.in);
System.out.println("Enter the number of item/s you purchased: ");
int numberOfItems = input.nextInt();
Discount discount = new Discount();
Double discountAmount = discount.getDiscountAmount(numberOfItems);
System.out.printf("The discount of %s items is %s%%",
numberOfItems,
Math.round(discountAmount*100));
这个问题还有更多“更流畅”的解决方案,这个解决方案的编写方式只是为了清楚起见。
推荐阅读
- javascript - React Redux:发布记录部分使用 onclick 功能
- apache-spark - 从 Spark 将许多文件写入镶木地板 - 缺少一些镶木地板文件
- sql-server - 将多级(元素)XML 文件导入 MS SQL Server 表
- r - 在使用 SparkR 编写镶木地板文件时设置架构
- sql - 如果不匹配,子查询返回所有行
- postgresql - 无法通过 postico 连接到 postgreSQL docker 容器
- angular - 订阅 cdk 滚动策略事件
- hibernate - Hibernate @ManyToOne 级联混合
- javascript - javascript ajax POST问题
- python - 通过熊猫中相同数据帧的切片索引设置数据帧列不起作用