-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATM.java
More file actions
84 lines (72 loc) · 2.63 KB
/
ATM.java
File metadata and controls
84 lines (72 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class ATM {
private HashMap<String, Double> accounts;
public ATM() {
accounts = new HashMap<String, Double>();
}
public void openAccount(String userId, double amount) {
if (accounts.containsKey(userId)) {
throw new Error("User: " + userId + " already exists.");
}
accounts.put(userId, amount);
}
public void closeAccount(String userId) {
if (accounts.containsKey(userId)) {
if (checkBalance(userId) == 0) {
accounts.remove(userId);
}
throw new Error("You need to withdraw $$$ before closing!");
}
throw new Error("Sorry, " + userId + " does not exist.");
}
public double checkBalance(String userId) {
if (accounts.containsKey(userId)) {
return accounts.get(userId);
}
throw new Error("No account found.");
}
public double depositMoney(String userId, double amount) {
if (!accounts.containsKey(userId)) {
throw new Error("Account doesn't exist, " + userId + " is broke AF.");
}
double addedBalance = accounts.get(userId) + amount;
accounts.replace(userId, addedBalance);
return addedBalance;
}
public double withdrawMoney(String userId, double amount) {
if (accounts.containsKey(userId)) {
double currentBal = accounts.get(userId);
if (currentBal >= amount) {
double newBal = currentBal - amount;
accounts.replace(userId, newBal);
return newBal;
}
throw new Error("Sorry " + userId + " , you're broke AF!");
} else {
throw new Error("User does not exist.");
}
}
public boolean transferMoney(String fromAccount, String toAccount, double amount) {
if (amount < 0) {
return false;
}
if (accounts.containsKey(fromAccount) && accounts.containsKey(toAccount)) {
withdrawMoney(fromAccount, amount);
depositMoney(toAccount, amount);
return true;
}
return false;
}
public void audit() throws IOException {
PrintWriter fileWriter = new PrintWriter(new BufferedWriter(new FileWriter("AccountAudit.txt")));
for (Map.Entry<String, Double> element : accounts.entrySet()) {
fileWriter.println("UserID: " + element.getKey() + " Balance: " + element.getValue());
}
fileWriter.close();
}
}