Search code examples
javaswingexceptionmethodsjtextfield

How to mdify the computeBalance() method making sure that amounts are positive and without cents?


How do I modify computeBalance() making sure that the amounts enetered in the JTextField is positive ( which I think I did) and is without cents? Example: 100.19 and -49.8 is not acceptable.

public class ATMbizlogic {

    private double totalBalance;
    private boolean rightPinEntered;



    /**
     * Creates a new instance of ATMbizlogic
     */
    public ATMbizlogic() 
    {
        totalBalance = 0.0;
        rightPinEntered =  true;
    }

    public void computeBalance(double withdraw, double deposit)
    throws ATMexception 
    {
        if(withdraw <=0)
            throw new ATMexception("Negative withdraw not allowed");


        if(deposit <=0)
            throw new ATMexception("Negative deposit not allowed");


         double balance = deposit - withdraw;

        totalBalance = totalBalance + balance;



    }



    public void checkPin(double pin)
    throws ATMexception 
    {
        if(pin <=0)
            throw new ATMexception("Negative pin not allowed");
        if(rightPinEntered == false)
            throw new ATMexception("Can not take another pin");
        if(pin<1111 || pin>9999)
            throw new ATMexception("Enter a valid pin");
        rightPinEntered = true;


    }




    public double getBalance()
    {
        return totalBalance;
    }
}

Solution

  • if(floor(withdraw) != withdraw)
        throw new ATMexception("Withdraw with cents is not allowed.");
    
    if(floor(deposit) != deposit)
        throw new ATMexception("Deposit with cents is not allowed.");
    

    That rounds the numbers down and checks if they are still the same number. If it isn't that means it had a decimal.