Kent Godfrey Kent Godfrey - 1 month ago 10
Java Question

Java- If else logic

I want to make it so that you cannot withdraw less that £0 from my savingAccount.Currently, I am using this method to control what happens:

//withdraw money if balance will = less than 0 after withdraw
public void withdraw(double amount){
if(balance>0){
balance= balance-amount;
updatebalance();
}else{
JOptionPane.showMessageDialog(null, "Insufficient funds", "Error", JOptionPane.ERROR_MESSAGE);
}
}


This logic works to an extent if the balance is already £0, but if the balance is greater that 0 it allows you to withdraw money into an overdraft.

I understand my problem but I dont really understand how I can fix it. I have tried searching online on other forums but I dont really know how to word it into a search... I appreciate any feedback and help I get.

TLDR: Make my IF statement not allow you to go under £0.

Thanks

Answer

It's a simple as comparing the existing balance with the requested amount, not zero.

if( balance >= amount ){
Comments