2016-05-01 6 views
-3

私は以下のメソッドに問題があります。現在と設定されているif/elseの条件を適用した場合、変数withdrawalAmountVarは二重の値を取得します(残高が100の場合、最終残高が98、最後の残高が80の場合は10になります)。どうして? =あなたが実際にmoneyAmountVar-withdrawalAmountVarにmoneyAmountVarの値が変更されている - あなたが操作を使用しているため変数がif/elseステートメントを適用してdouble値を取得する

public void makeWithdrawalButton() 
{ 
    //transfer user's input into withdrawalAmountVar 
    withdrawalAmountVar = Integer.parseInt(text5.getText()); 

    //check if withdrawal should be allowed according to overdraft set 
/* 
if ((moneyAmountVar -= withdrawalAmountVar) < overdraftVar) 
{ 
    JOptionPane.showMessageDialog(null, "Withdrawal amount exceeds overdraft"); 
    text5.setText(""); 
} 

else 
{ 
*/ 

    try 
    { 
     //make withdrawal from current deposit amount 
     moneyAmountVar -= withdrawalAmountVar; 

     output = new DataOutputStream(new FileOutputStream("datafile.dat")); 
     output.writeInt(accountNumberVar); 
     output.writeUTF(firstNameVar); 
     output.writeUTF(lastNameVar); 
     output.writeInt(moneyAmountVar); 
     output.close(); 
    } 
    catch(IOException e) 
    { 
     System.err.println("Cannot make withdrawal"); 
     System.exit(1); 
    } 
} 
+1

- tryブロックの開始における状態の場合に= withdrawalAmountVar' Oneと 別 –

+0

その型であるint型 – JohnSnow

+0

moneyAmountVar- =は実際にあなたの' if'条件は 'moneyAmountVarある – DarkV1

答えて

1

問題が

if ((moneyAmountVar -= withdrawalAmountVar) < overdraftVar) 

です。このような操作などを使用すると、lValueは条件またはループに関係なく常にそれに応じて変更されます。修正するには :

int temp = moneyAmountVar - withdrawalAmountVar; 

if ((temp) < overdraftVar) 

temp変数はmoneyAmountの値が変更されないことを確認します。あなたが二回 `moneyAmountVar実行されている

+0

ありがとう、私はif((moneyAmountVar - withdrawalAmountVar) JohnSnow

関連する問題