sirio sirio - 7 months ago 10
Java Question

variable gets double value by applying an if/else statement

I have an issue with the following method. If I apply the

if/else
condition which is currently set as a comment
/* */
, the variable
withdrawalAmountVar
get double value (if balance is 100 and I withdraw 1 final balance is 98, if I withdraw 10 the final balance is 80). Why?

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);
}
}

Answer

The problem is

if ( (moneyAmountVar -= withdrawalAmountVar) < overdraftVar)

because you used the operation -= you are actually changing the value of moneyAmountVar to moneyAmountVar-withdrawalAmountVar. When you use this operation or something like it, the lValue will always change accordingly, no matter if it is in a conditional or loop. To Fix:

int temp = moneyAmountVar - withdrawalAmountVar;

 if ( (moneyAmountVar -= withdrawalAmountVar) < overdraftVar)

A Temp variable will make sure that the value of moneyAmount will not change.

Comments