java - Need to show "Insufficient Funds" for negative amounts -
i need throw exception "insufficient funds" when user withdrawals more amount in initialaccountbalance (which equals 500.00). however, unsure put exception.
public static void main(string[] args) { scanner in = new scanner(system.in); double initialaccountbalance = 500.00; system.out.print("enter 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"); } }
you place if
right after user enters amount withdrawal 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 want throw own exception have create new class extends exception
@chenchuk mentioned in comments.
public class insufficientfundsexception extends exception{ //if need can overwrite method of exception here }
so can throw insufficientfundsexception
in 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 have provide way of handling exception either using try-catch block or adding throws declaration method head. should up, it's explain in depth here...
hope helps bit (:
Comments
Post a Comment