Challenge: Safe Bank Account
Write a class Account with a private balance starting at 0, and methods deposit(int), withdraw(int) and getBalance(). Deposits must be positive. A withdrawal that is more than the balance must be refused.
Read a number of commands n, then n commands like deposit 500 or withdraw 200. For a refused withdrawal print Insufficient funds. At the end print Balance: <balance>.
Input
First n, then n lines: a word and a whole number.
Output
One line per refused withdrawal, then the final balance.
Example
Input
3 deposit 500 withdraw 200 withdraw 400
Output
Insufficient funds Balance: 300
Hints
Make withdraw return a boolean: true if it worked, false if refused.
Compare command words with equals().
Solution explanation
Because balance is private, the only way to change it is through methods that check the amount.
Show solution
import java.util.Scanner;
class Account {
private int balance;
void deposit(int amount) {
if (amount > 0) balance += amount;
}
boolean withdraw(int amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
int getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Account acc = new Account();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
int amount = sc.nextInt();
if (cmd.equals("deposit")) {
acc.deposit(amount);
} else if (!acc.withdraw(amount)) {
System.out.println("Insufficient funds");
}
}
System.out.println("Balance: " + acc.getBalance());
}
}You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module