Write a class that guards its balance, so no code outside it can make the balance wrong.
What to build
A program that runs commands against one bank account.
Requirements
- Write
class Accountwith a privatebalance,deposit(amount: number): void,withdraw(amount: number): booleanand a gettertotal. deposit Kadds K;withdraw Ktakes K away if the balance is at least K, and otherwise printsinsufficient funds;balanceprintsbalance: B.- An amount that is not more than 0 prints
invalid amountand changes nothing.
Input
Line 1: n. Then n commands.
Output
One line per balance command and per refused command.
Constraints
1 ≤ n ≤ 100; amounts are whole numbers.
Example
Input:
5
deposit 100
withdraw 30
balance
withdraw 100
balance
Output:
balance: 70
insufficient funds
balance: 70
Why it works
With the balance private, the only ways to change it are the two methods, so the rules about invalid amounts and overdrawing are written once and can never be skipped.
Examples
Example 1 · Input
5 deposit 100 withdraw 30 balance withdraw 100 balance
Expected output
balance: 70 insufficient funds balance: 70
Example 2 · Input
3 deposit -5 withdraw 0 balance
Expected output
invalid amount invalid amount balance: 0
Hints
Hint 1
Keep the balance in a private field and change it only in deposit and withdraw.
Hint 2
withdraw can return a boolean saying whether it worked.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
class Account {
private balance = 0;
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): boolean {
if (amount > this.balance) return false;
this.balance -= amount;
return true;
}
get total(): number {
return this.balance;
}
}
const account = new Account();
const n = Number(read());
for (let i = 0; i < n; i++) {
const [command, text] = read().split(" ");
if (command === "balance") {
console.log("balance: " + account.total);
continue;
}
const amount = Number(text);
if (!(amount > 0)) {
console.log("invalid amount");
} else if (command === "deposit") {
account.deposit(amount);
} else if (!account.withdraw(amount)) {
console.log("insufficient funds");
}
}