Bank Account Simulator

Problem

Simulate a bank account that starts with balance 0. Each input line is a command: deposit X, withdraw X or balance. Print one line for each command. For a good deposit or withdrawal print OK. If X is not positive print Error: invalid amount. If a withdrawal is larger than the balance print Error: insufficient funds (the balance does not change). For balance print Balance: <value>.

Constraints

  • 1 <= number of commands <= 1000
  • 0 <= X <= 10^9 (X may be negative or zero for error tests)

Examples

Input

deposit 100
withdraw 30
balance

Output

OK
OK
Balance: 70

Solutions

Best approachTime O(commands)Space O(commands)

The BankAccount class hides its balance. Nobody can set it directly, so the rules (positive amount, enough money) can not be skipped. Exceptions report errors without special return values.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process commands line by line.
 * Input   : Several lines of commands.
 * Output  : One answer line for each command.
 * Approach: A class with private data and checked methods.
 * Time    : O(commands)
 * Space   : O(commands)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Step 1: The class keeps its data private. Only its methods can change the balance (encapsulation).
        static class BankAccount {
            private long balance = 0;

            // Step 2: Each method checks its input and throws an exception for a bad request.
            void deposit(long amount) {
                if (amount <= 0) {
                    throw new IllegalArgumentException("invalid amount");
                }
                balance += amount;
            }

            void withdraw(long amount) {
                if (amount <= 0) {
                    throw new IllegalArgumentException("invalid amount");
                }
                if (amount > balance) {
                    throw new IllegalStateException("insufficient funds");
                }
                balance -= amount;
            }

            long getBalance() {
                return balance;
            }
        }

    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String[] lines) {
        BankAccount account = new BankAccount();
        String[] output = new String[lines.length];

        for (int i = 0; i < lines.length; i++) {
            String[] parts = lines[i].split(" ");

            // Step 3: Run the command. A failed request throws an exception, and we print its message.
            try {
                if (parts[0].equals("deposit")) {
                    account.deposit(Long.parseLong(parts[1]));
                    output[i] = "OK";
                } else if (parts[0].equals("withdraw")) {
                    account.withdraw(Long.parseLong(parts[1]));
                    output[i] = "OK";
                } else {
                    output[i] = "Balance: " + account.getBalance();
                }
            } catch (IllegalArgumentException | IllegalStateException error) {
                output[i] = "Error: " + error.getMessage();
            }
        }
        return output;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                all.add(line);
            }
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(String.join("\n", solve(lines)));
    }
}
Hints (2)
  1. Why is the balance field private?
  2. Which exception type fits a bad argument?