[英]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.