Search code examples
javastructurebank

How to print error message when my withdraw input is greater than my cash balance?


I'm having a problem with my java bank program, wherein the user can withdraw what is greater from the cash balance. Same thing with my other features which are "Payment" and "Send Money". How do I have this code like it uses and 'else if' statement or??? I am stumped. Please help. Thanks.

case "Withdraw": //withdraw money from account
            if(people.get(accIndex).getMoney()<=0) { //if the user does not have enough funds
                JOptionPane.showMessageDialog(null, "You Dont Have Enough Funds In Your Account!", "Javank", JOptionPane.WARNING_MESSAGE);
            }
            else {
            System.out.print("Input amount to withdraw: ");
            double withmoney = in.nextDouble();
            people.get(accIndex).setMoney(people.get(accIndex).getMoney()-withmoney); //gets info from accIndex and withdraws money from account
            JOptionPane.showMessageDialog(null, "Successfully withdrew: "+withmoney,"Javank",JOptionPane.INFORMATION_MESSAGE);
            LocalDateTime myDateObj2 = LocalDateTime.now(); //create local date and time object
            String formattedDate2 = myDateObj2.format(myFormatObj); //store it to a string (formatted)
            checktrans.push("Withdrew "+withmoney+" @ "+formattedDate2); //add to transaction stack
            }
            break;

Solution

  • I would think it's not relevant if the user has a positive balance at the start. Instead I would check if the balance would get below zero if the requested amount would have been withdrawn.

    Something like

    double withmoney = in.nextDouble();
    if((people.get(accIndex).getMoney() - withmoney) < 0.0) {
        //the user does not have enough funds
    }
    else {
        //allow withdrawal
    }