我以为我的做法是正确的,但是当我尝试在“收银机”中拆分付款时,它在第二次和第一次付款上都返回了正确的找零,但在第二次付款上,它包含我放置的第三个 if 语句,并且它也给出了找零。
例如:
Price: $100.00
Sales tax = $6.00
Total amount due = $106.00
Payment = $50.00
Amount Remaining: $56.00
Payment $50.00
Amount Remaining: $6.00
Your Change Is: $44.00
这是有问题的代码段。如有任何帮助,我们将不胜感激。
public void makePayment (double payment){
if (payment < 0){
System.out.println("Insufficient Funds. Please Use Another Method Of Payment");
}
if (payment < currentAmountDue ){
currentAmountDue = currentAmountDue - payment;
System.out.println("Amount Remaining: " + fmt.format(currentAmountDue));
dailySales = currentAmountDue + dailySales;
}
if (payment > currentAmountDue){
dailySales = dailySales + currentAmountDue;
currentAmountDue = payment - currentAmountDue;
System.out.println("Your Change Is: " + fmt.format(currentAmountDue));
numberOfCustomers = numberOfCustomers + 1;
dailySales = currentAmountDue + dailySales;
}
if (payment == currentAmountDue){
dailySales = dailySales + currentAmountDue;
numberOfCustomers = numberOfCustomers + 1;
currentAmountDue = 0;
System.out.println("Thank you for your money!");
}
}
如果您查看第二次付款的代码,很容易发现这一点。
输入后currentAmountDue=56
和 payment=50
,所以
if (payment < currentAmountDue )
这是真的,你也这么做
currentAmountDue = currentAmountDue - payment;
现在 currentAmountDue=6
并且仍然 payment=50
并且执行下一个 if
语句:
if (payment > currentAmountDue){
其计算结果也为true
。
您只想执行一个 if
分支,因此最好将除第一个之外的所有 if
分支更改为 else if
。
我是一名优秀的程序员,十分优秀!