简体   繁体   English

在While循环中更新变量

[英]Updated Variable in a While Loop

I have this while loop that runs as a user input fee is larger then a transaction amount. 我有这个while循环,当用户输入费用大于交易金额时运行。 For example, if the fee is $4 and you only pay $2, it will say you still owe $2 and prompt you to enter more payments. 例如,如果费用是4美元,而您只支付2美元,它将表示您仍欠2美元,并提示您输入更多付款。 The problem is that I cannot figure out how to update the variable transaction after a payment if it is still short. 问题是,如果付款仍然很短,我无法弄清楚如何在付款后更新可变交易。 After it asks for another payment, say you are still short of the $4 and pay another $1, that will give you a total of $3 and the program should say you are still short by $1. 在它要求再次付款之后,说您仍然短缺4美元,再支付1美元,这将使您总共获得3美元,而程序应说您仍然短缺1美元。 Nonetheless, the program still says you are short by the original amount, ie $2. 尽管如此,该程序仍然说您短缺原始金额,即2美元。

while (transaction < feeSum)
{
    double underPay = feeSum - transaction;
    System.out.println("The transaction did not meet the fee by $" + underPay);
    System.out.println("Please enter another payment to complete the balance.");

    System.out.println("Enter a number of payments.");
    int paymentSize2 = keyboard.nextInt();
    double[] payments2 = new double[paymentSize2];

    System.out.println("Enter " + payments2.length + " payment(s).");
    double paymentSum2 = 0;
    for(int i = 0; i < payments2.length; i++)
    {
        payments2[i] = keyboard.nextDouble();
        paymentSum2 = paymentSum2 + payments[i];
        transaction +=  paymentSum2; //<<<<<<< Shouldn't this update transaction? 
    }   // The second time around it should say the trans did not meet fee by $1

    if (paymentSum2 == underPay)
    {
        System.out.println("There is now no outstanding balance.");
        break;
    }

I remade your code a little, this will work, however it doesn't contain all that extra stuff you implemented. 我稍微修改了一下代码,这可以工作,但是其中不包含您实现的所有额外内容。 I don't really understand why you need those arrays. 我不太了解为什么需要这些数组。 This code doesn't handle if you pay more than you should, however that could easily be implemented in the last lines of the while loop. 如果您支付的费用超出您的预期,则此代码将无法处理,但是可以在while循环的最后几行中轻松实现。

double underPay = feeSum - transaction;
            while (underPay != 0) {
                System.out.println("The transaction did not meet the fee by $" + underPay);
                System.out.println("Please enter another payment to complete the balance.");
                int paymentSizeNext = keyboard.nextInt();
                underPay -= paymentSizeNext;


            }
            System.out.println("There is now no outstanding balance.");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM