Java Tutorial
Java Project: Bank System
An Account class with deposit, withdraw, and a printed statement. Balance never goes negative.
What you will build
An account holds a balance. deposit adds. withdraw refuses if the amount is larger than the balance.
Account methods
Example
class Account {
private double balance;
Account(double start) { balance = start; }
void deposit(double n) { if (n > 0) balance += n; }
boolean withdraw(double n) {
if (n <= 0 || n > balance) return false;
balance -= n;
return true;
}
void statement() { System.out.printf("balance: %.2f%n", balance); }
}
public class Main {
public static void main(String[] args) {
Account a = new Account(100);
a.deposit(25);
System.out.println(a.withdraw(40) ? "ok" : "refused");
System.out.println(a.withdraw(1000) ? "ok" : "refused");
a.statement();
}
}Practice
- Compile the complete program at
/java/try. - Change one input value and compile again.
- Replace a hardcoded number with
Scannerwhen you want typed input.