简体   繁体   中英

Updated Variable in a While Loop

I have this while loop that runs as a user input fee is larger then a transaction amount. 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. 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. Nonetheless, the program still says you are short by the original amount, ie $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.

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.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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