Search code examples
javaexceptionthrow

Need to show "Insufficient Funds" for negative amounts


I need to throw an exception for "insufficient Funds" when a user withdrawals more than the amount in initialAccountBalance (which equals 500.00). However, I am unsure where to put the exception.

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    double initialAccountBalance = 500.00;

    System.out.print("Enter a transaction type (Balance, Deposit, or Withdrawal): ");
    String transactionType = in.nextLine();

    if (transactionType.equalsIgnoreCase("Balance")){
        System.out.println("Balance " +initialAccountBalance);
        System.out.println();

    } else if (transactionType.equalsIgnoreCase("Deposit")){
        System.out.println("Enter deposit: ");
        int deposit = in.nextInt();
        double balance = initialAccountBalance + deposit;
        System.out.printf("Account Balance: %8.2f", balance);

    } else if(transactionType.equalsIgnoreCase("Withdrawal")){
        System.out.println("Enter withdrawal: ");
        int withdrawal = in.nextInt();
        double balance = initialAccountBalance - withdrawal;
        System.out.printf("Account Balance: %8.2f", balance);

    } else {
        System.out.println("Invalid transaction type");
    }
}

Solution

  • You could place a if right after the user enters the amount to withdrawal like this:

    //...
    System.out.println("Enter withdrawal: ");
    int withdrawal = in.nextInt();
    if (withdrawal > initialAccountBalance)
        throw new RuntimeException("Insufficient Funds");
    double balance = initialAccountBalance - withdrawal;
    System.out.printf("Account Balance: %8.2f", balance);
    //...
    

    If you want to throw your own exception you have to create a new class that extends Exception like @chenchuk mentioned in the comments.

    public class InsufficientFundsException extends Exception{
        //if you need to you can Overwrite any method of Exception here
    }
    

    So you can throw the InsufficientFundsException in your main method:

    //...
    System.out.println("Enter withdrawal: ");
    int withdrawal = in.nextInt();
    if (withdrawal > initialAccountBalance)
        throw new InsufficientFundsException();
    double balance = initialAccountBalance - withdrawal;
    System.out.printf("Account Balance: %8.2f", balance);
    //...
    

    but you would have to provide some way of handling the exception by either using a try-catch block or adding a throws declaration to the method head. But you should look that up, it's to much to explain in depth here...

    Hope this helps you a bit (: