-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankAccount.java
More file actions
72 lines (57 loc) · 2.02 KB
/
Copy pathBankAccount.java
File metadata and controls
72 lines (57 loc) · 2.02 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
import java.util.Scanner;
// Custom exception class
class InsufficientFundsException extends Exception {
InsufficientFundsException(String s) {
super(s);
}
}
// BankAccount class
class BankAccount {
String name;
double account_balance;
// Default constructor
BankAccount() {
this.name = "";
this.account_balance = 0;
}
// Parameterized constructor
BankAccount(String name, double account_balance) {
this.name = name;
this.account_balance = account_balance;
}
// Method to withdraw amount
void withdraw(double amount) throws InsufficientFundsException {
if (amount > account_balance) {
throw new InsufficientFundsException("Insufficient balance");
} else {
account_balance -= amount;
System.out.println("Withdrawal successful! Remaining balance: " + account_balance);
}
}
// Method to display account details
void display() {
System.out.println("Name: " + this.name);
System.out.println("Account balance: " + this.account_balance);
}
// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get account details from user
System.out.println("Please enter your name:");
String name = sc.nextLine();
System.out.println("Please enter your account balance:");
double account_balance = sc.nextDouble();
// Create BankAccount object
BankAccount B1 = new BankAccount(name, account_balance);
// Show account details
B1.display();
// Get withdrawal amount and try to withdraw
System.out.println("Please enter the amount to withdraw:");
double withdraw_amount = sc.nextDouble();
try {
B1.withdraw(withdraw_amount);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}