繁体   English   中英

在While循环中更新变量

[英]Updated Variable in a While Loop

我有这个while循环,当用户输入费用大于交易金额时运行。 例如,如果费用是4美元,而您只支付2美元,它将表示您仍欠2美元,并提示您输入更多付款。 问题是,如果付款仍然很短,我无法弄清楚如何在付款后更新可变交易。 在它要求再次付款之后,说您仍然短缺4美元,再支付1美元,这将使您总共获得3美元,而程序应说您仍然短缺1美元。 尽管如此,该程序仍然说您短缺原始金额,即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;
    }

我稍微修改了一下代码,这可以工作,但是其中不包含您实现的所有额外内容。 我不太了解为什么需要这些数组。 如果您支付的费用超出您的预期,则此代码将无法处理,但是可以在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