我有一个必须完成的小项目才能找到工作。我相信你们已经在这里看到了这个项目。我想要两件事,关于如何获得正确答案的提示,以及迄今为止对我的解决方案的同行评审。
public class OrderMethod {
static Map<String, BigDecimal> newOrder;
static final BigDecimal BASICSALES = new BigDecimal(.10);
static final BigDecimal IMPORTSALES = new BigDecimal(.05);
static final BigDecimal BASICANDIMPORTSALES = new BigDecimal(.15);
static final BigDecimal Rounding = new BigDecimal(0.05);
static BigDecimal total = new BigDecimal(0);
public void convertOrders() throws IOException {
ReadFile readfile = new ReadFile();
ArrayList<String> order = readfile.getFile();
newOrder = new LinkedHashMap<String, BigDecimal>();
for(String i : order) {
String[] splitOrder = i.split("at\\ ");
newOrder.put(splitOrder[0], new BigDecimal(splitOrder[1]));
}
}
public void calculate() {
newOrder.forEach((k, v) -> {
if(!((k.contains("chocolate")) || k.contains("book") || k.contains("pill")) && k.contains("import")){
v = v.multiply(BASICANDIMPORTSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Both " + k + " tax: $" + v);
newOrder.put(k, v);
}
else {
if(!(k.contains("chocolate")|| k.contains("book") || k.contains("pill"))) {
v = v.multiply(BASICSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Basic " + k + " tax: $" + v);
newOrder.put(k, v);
}
if(k.contains("import")) {
v = v.multiply(IMPORTSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Import " + k + " tax: $" + v);
newOrder.put(k, v);
}
}
total = total.add(v);
});
}
public void print() {
newOrder.forEach((k, v) -> {
System.out.println(k + ": $" + v);
});
System.out.println("Total: $" + total);
}
public static void main(String[] args) throws IOException {
OrderMethod om = new OrderMethod();
om.convertOrders();
om.calculate();
om.print();
}
}
所以我所做的是让程序读取包含输入的文本文件,例如
Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
以下是解决方案列表: 输出:
Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15
Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
我的计算有一点问题。不管怎样,我对输入 2 和 3 的答案似乎都少了几个小数位。输入 2 获得 65.12 美元,输入 3 获得 74.64 美元。 我希望获得有关如何更好地汇总我的答案的帮助,以及到目前为止您对我的代码有何看法。
最佳答案
我不明白你的代码,但我在考试时必须这样做。
我像这样使用运算符 % 并且它有效。
if((数字 * 100)%10 >= 5)
关于java - 如何在 Java 中四舍五入到最接近的 0.05?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60013918/