You should use ArrayList
instread of arrays here, but more to the point, you should aim to use a databasehere, even if it is just an in-memory temporary database. Also, the printDeposit
method is badly named; that would probably correspond to printing a deposit receipt. You'd want your logic to be something like:
Console console = System.getConsole();
if (console == null) {System.exit(42)}
while(true) (
String option = console.readLine("What would you like to ask this ATM? %d to Quit, %d to deposit, %d to withdraw:", 0, 1, 2;
switch (option) {
case "1": acceptDeposit(); break;
case "2": acceptWithdrawl(); break;
case "0": quit(); break;
default: break;
}
}
Now, you need to write the acceptDeposit
and acceptWithdrawl
methods. In database terms, you'd want a balance
table and a transaction
table. In Java terms, you'd want classes like this:
public class Transaction {
enum Type {DEPOSIT, WITHDRAWL, INTEREST};
private Long userId;
private Type type;
private BigDecimal amount;
private Date date; // Switch to Joda-Time or its Java 8 equivalent when you can.
// getters, setters, etc.
public getBalanceChange() {
if (type != WITHDRAWL) {
return amount;
} else {
return amount.negate();
}
}
}
Do you see why you want the user id?
Your application would have a list of transactions, and uneless you keep a map that maps user ids to balances, you'd want a balance method:
public BigDecinmal balance(Long userId) {
BigDecimal balance = new BigDecimal("0.00");
for (Transaction t: transactionList) {
if (userId.equals(t.getUserId())) {
balance = balance.add(t.getBalanceChange());
}
}
}
With a database table, you'd do an UPDATE to the database. Were this app running continually, you'd schedule jobs to compute interest, probably using the Java Quartz library. For a student application, you'd simulate it by having a method:
private void applyInterest(Date from, Date to){...}
In fact, that's an argument against using GregorianCalendar
and getting one for the time of each transaction; in practical use, each session will be part of a single day. Instead, have a Date currentDate
and a Date interestLastApplied
variable, and bump currentDate
up periodically.