Repository navigation
Expand file tree
/
Copy pathBankAccount.java
More file actions
90 lines (74 loc) · 2.37 KB
/
Copy pathBankAccount.java
File metadata and controls
90 lines (74 loc) · 2.37 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
85
86
87
88
89
90
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// Method to withdraw money
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for this withdrawal");
}
balance -= amount;
}
// Method to get the current balance
public double getBalance() {
return balance;
}
/**
* @param args
*/
public static void main(String[] args) {
// Create a BankAccount object
BankAccount account = new BankAccount(1000.0);
// Deposit money
account.deposit(500.0);
System.out.println("Current balance after deposit: " + account.getBalance());
// Attempt to withdraw money
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// Method to withdraw money
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
try {
account.withdraw(2000.0);
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}
// Check balance after attempted withdrawal
System.out.println("Current balance after attempted withdrawal: " + account.getBalance());
// Successful withdraw
try {
account.withdraw(300.0);
System.out.println("Withdrawal successful.");
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}
// Final balance
System.out.println("Final balance: " + account.getBalance());
}
}