I am working on an assignment where the user is allowed to withdraw and deposit money into their account. But it is my responsibility to have the code catch whenever the user goes over 5 transactions and then charge their account with $1. I so far created for the withdraw method this code :
public double withdraw(double amount) throws Exception {
if( numtransactions <5){
this.numtransactions++;
return balance-amount;
// Stub
}
else {
this.numtransactions++;
this.balance-1;
return balance-amount;
}
return balance - amount;
}
Eclipse gives me an error warning that at the line this.balance-1;
the "-" is considered a syntax error.
How can I fix this issue and does this code make sense to do what it is intended to do?
My Deposits method is built similarly but with a few if and else statements to restrict other things and also have a few issues. But I am hoping to first cover this withdraw method and utilize what I learn from this method onto the deposits.
Thanks Tom
Edit:
I have implemented the use of declaring this.balance with balance-=1 and both my withdraws method and deposit method are working correctly! Thank you for making my first experience on stackoverflow and amazing one!!
In the line
this.balance - 1;
you are not assigning the result of that operation to any variable. If you want to reduce balance
, you can use either of these (all are equivalent):
this.balance = this.balance - 1;
this.balance -= 1;
this.balance--;
Also, each with each withdraw, you would like to modify the balance
:
this.balance -= amount;
Why "-" is considered a syntax error?
Java expects a variable in the left-hand part of an assignment and an expression in the right-hand part. When you do, for example:
2 - 1;
an assignment operator (=
) is expected, because you cannot have an expression (in this case 2 - 1
) in the left-hand part.