Java assertion exception

advertisements

I've made s simple program to let the user withdraw a certain amount out of a bank account, and if they withdraw too much it will cause an AssertionError, how do I get it to write out the error?

import java.util.Scanner;

public class Withdraw {

    public static void main(String[]args){
        Scanner a = new Scanner(System.in);

        int t = 10000;
        System.out.println("Withdraw or Deposit");
        String in = a.next();
        System.out.println("Enter your value");
        int wd = a.nextInt();

        if(in.equals("withdraw")){
            int b;
            b = t - wd;
            System.out.println(t);
            if (b < 0){
                throw new AssertionError();
            }
        }
    }

}


I'll assume you want your AssertionError to include some information on the balance. You're using the constructor AssertionError(). According to the documentation, you can also use the constructor AssertionError(Object detailMessage) where the object will be converted to a string. So you can do this:

throw new AssertionError("Oh no, your balance " + b + " is negative!");

PS - Your two if statements have different spacing e.g. if( versus if (. This is an example of "code smell" - not a true error, but poor style indicating carelessness. Try to keep these little things consistent going forward and your code will look cleaner and more readable