Question: Question: Write a Java program that simulates a simple bank account. The program should have the following features: Create a BankAccount class with the following
Question:
Write a Java program that simulates a simple bank account. The program should have the following features:
Create a BankAccount class with the following attributes:
- accountNumber (String)
- accountHolder (String)
- balance (double)
Implement a constructor to initialize the accountNumber and accountHolder when an instance of BankAccount is created.
Implement methods to perform the following actions:
- deposit(double amount): This method should allow the user to deposit money into the account.
- withdraw(double amount): This method should allow the user to withdraw money from the account if the balance is sufficient.
- getBalance(): This method should return the current balance of the account.
Include error handling to prevent overdrawing (i.e., withdrawing more money than is available in the account). If a withdrawal would result in a negative balance, display an error message.
Create a Main class to test the BankAccount class. Instantiate a BankAccount object, perform deposits and withdrawals, and display the balance after each transaction.
Provide appropriate input validation and error messages for invalid input (e.g., negative deposit amount).
Sample usage of the program:
BankAccount account = new BankAccount("123456789", "John Doe"); System.out.println("Initial Balance: " + account.getBalance()); account.deposit(1000.0); System.out.println("After deposit: " + account.getBalance()); account.withdraw(500.0); System.out.println("After withdrawal: " + account.getBalance()); account.withdraw(700.0); // Should display an error message.
Please write the Java code for the BankAccount class and the Main class to implement this functionality.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
