Bank with Exceptions
Completed
Commands: open NAME, deposit NAME AMT, withdraw NAME AMT, transfer FROM TO AMT, balance NAME. Use a custom BankException for unknown accounts, duplicates, non-positive amounts and insufficient funds, printing error: MESSAGE.
Input
n, then n commands.
Output
Balances and errors.
Example
Input
10 open ann open bob deposit ann 100 transfer ann bob 30 withdraw bob 50 balance ann balance bob open ann deposit cy 5 deposit ann -1
Output
error: insufficient funds in bob ann: 70 bob: 30 error: ann already exists error: no account cy error: amount must be positive
Editor
Java
Hints
Read all arguments of a command before anything can throw, so input stays in step.
transfer checks the target first, then reuses withdraw and deposit.
Solution explanation
Every rule violation is a BankException, caught in exactly one place in the command loop.
Show solution
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class BankException extends Exception {
BankException(String message) {
super(message);
}
}
class Bank {
private final Map<String, Long> accounts = new HashMap<>();
void open(String name) throws BankException {
if (accounts.containsKey(name)) throw new BankException(name + " already exists");
accounts.put(name, 0L);
}
long balance(String name) throws BankException {
Long b = accounts.get(name);
if (b == null) throw new BankException("no account " + name);
return b;
}
void deposit(String name, long amount) throws BankException {
if (amount <= 0) throw new BankException("amount must be positive");
accounts.put(name, balance(name) + amount);
}
void withdraw(String name, long amount) throws BankException {
if (amount <= 0) throw new BankException("amount must be positive");
long b = balance(name);
if (amount > b) throw new BankException("insufficient funds in " + name);
accounts.put(name, b - amount);
}
void transfer(String from, String to, long amount) throws BankException {
balance(to);
withdraw(from, amount);
deposit(to, amount);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
try {
switch (cmd) {
case "open": bank.open(sc.next()); break;
case "deposit": bank.deposit(sc.next(), sc.nextLong()); break;
case "withdraw": bank.withdraw(sc.next(), sc.nextLong()); break;
case "transfer": bank.transfer(sc.next(), sc.next(), sc.nextLong()); break;
default:
String name = sc.next();
System.out.println(name + ": " + bank.balance(name));
}
} catch (BankException e) {
System.out.println("error: " + e.getMessage());
}
}
}
}