收银机退还余额加上二次付款的变更

时间:2015-02-17 08:21:34

标签: java if-statement

我认为我这样做是正确的,但是当我尝试在我的“收银机”中拆分付款时,它在第二次付款和第一次付款时都返回了正确的更改,但在第二次付款时它包含我放置的第三个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!");
    }
}

1 个答案:

答案 0 :(得分:0)

如果您完成第二次付款的代码,很容易发现。

进入currentAmountDue=56payment=50后,

if (payment < currentAmountDue )

是真的你做了

 currentAmountDue = currentAmountDue - payment;

现在currentAmountDue=6仍然是payment=50并执行下一个if - 声明:

if (payment > currentAmountDue){

其中也评估为true

您只想执行一个if - 分支,因此您最好将if的所有内容更改为else if以外的其他内容。