Question

In: Computer Science

Modify the BankAccount class to throw IllegalArgumentException exceptions, create your own three exceptions types. when the...

Modify the BankAccount class to throw IllegalArgumentException exceptions, create your own three exceptions types. when the account is constructed with negative balance, when a negative amount is deposited, or when an amount that is not between 0 and the current balance is withdrawn. Write a test program that cause all three exceptions occurs and catches them all.

/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;

/**
Constructs a bank account with a zero balance
*/
public BankAccount()
{   
balance = 0;
}

/**
Constructs a bank account with a given balance
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{   
if (initialBalance < 0)
throw new NegativeBalanceException(
"Cannot create account: " + initialBalance + " is less than zero");   
  
balance = initialBalance;
}

/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
if (amount < 0)
throw new NegativeAmountException(
"Deposit of " + amount + " is less than zero");
double newBalance = balance + amount;
balance = newBalance;
}

/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{   
if (amount < 0)
throw new NegativeAmountException(
"Withdrawal of " + amount + " is less than zero");
  
if (amount > balance)
throw new InsufficientFundsException(
"Withdrawal of " + amount + " exceeds balance of " + balance);
  
double newBalance = balance - amount;
balance = newBalance;
}

/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{   
return balance;
}
}
---------------

/**
A class to test the BankAccount class.
*/
public class BankAccountTester2
{
public static void main(String[] args)
{
BankAccount harrysChecking = new BankAccount();
  
try
{
harrysChecking.deposit(300);
System.out.println("success");
}
catch (IllegalArgumentException e)
{
System.out.println("exception");
}
System.out.println("Expected: success");

try
{
harrysChecking.withdraw(100);
System.out.println("success");
}
catch (IllegalArgumentException e)
{
System.out.println("exception");
}
System.out.println("Expected: success");

try
{
harrysChecking.deposit(-100);
System.out.println("success");
}
catch (IllegalArgumentException e)
{
System.out.println("exception");
}
System.out.println("Expected: exception");

try
{
harrysChecking.withdraw(300);
System.out.println("success");
}
catch (IllegalArgumentException e)
{
System.out.println("exception");
}
System.out.println("Expected: exception");
}
}
-------------------------

Hint:

/**
This exception reports a negative initial balance on a bank account.
*/
public class NegativeBalanceException extends RuntimeException
{
public NegativeBalanceException()
{
}

public NegativeBalanceException(String message)
{
super(message);
}
}

Solutions

Expert Solution

Code For Above Problem:

BankAccount.java

/**
 * A bank account has a balance that can be changed by deposits and withdrawals.
 */
public class BankAccount {
        private double balance;

        /**
         * Constructs a bank account with a zero balance
         */
        public BankAccount() {
                balance = 0;
        }

        /**
         * Constructs a bank account with a given balance
         * 
         * @param initialBalance the initial balance
         */
        public BankAccount(double initialBalance) {
                if (initialBalance < 0)
                        throw new NegativeBalanceException("Cannot create account: " + initialBalance + " is less than zero");

                balance = initialBalance;
        }

        /**
         * Deposits money into the bank account.
         * 
         * @param amount the amount to deposit
         * @throws NegativeAmountException 
         */
        public void deposit(double amount) throws NegativeAmountException {
                if (amount < 0)
                        throw new NegativeAmountException("Deposit of " + amount + " is less than zero");
                double newBalance = balance + amount;
                balance = newBalance;
        }

        /**
         * Withdraws money from the bank account.
         * 
         * @param amount the amount to withdraw
         * @throws NegativeAmountException 
         * @throws InsufficientFundsException 
         */
        public void withdraw(double amount) throws NegativeAmountException, InsufficientFundsException {
                if (amount < 0)
                        throw new NegativeAmountException("Withdrawal of " + amount + " is less than zero");

                if (amount > balance)
                        throw new InsufficientFundsException("Withdrawal of " + amount + " exceeds balance of " + balance);

                double newBalance = balance - amount;
                balance = newBalance;
        }

        /**
         * Gets the current balance of the bank account.
         * 
         * @return the current balance
         */
        public double getBalance() {
                return balance;
        }
}

BankAccountTester2.java

/**
 * A class to test the BankAccount class.
 */
public class BankAccountTester2 {
        public static void main(String[] args) {
                BankAccount harrysChecking = new BankAccount();

                try {
                        harrysChecking.deposit(300);
                        System.out.println("success");
                } catch (IllegalArgumentException | NegativeAmountException e) {
                        System.out.println("exception");
                }
                System.out.println("Expected: success");

                try {
                        harrysChecking.withdraw(100);
                        System.out.println("success");
                } catch (IllegalArgumentException | NegativeAmountException | InsufficientFundsException e) {
                        System.out.println("exception");
                }
                System.out.println("Expected: success");

                try {
                        harrysChecking.deposit(-100);
                        System.out.println("success");
                } catch (IllegalArgumentException | NegativeAmountException e) {
                        System.out.println("exception");
                }
                System.out.println("Expected: exception");

                try {
                        harrysChecking.withdraw(300);
                        System.out.println("success");
                } catch (IllegalArgumentException | NegativeAmountException | InsufficientFundsException e) {
                        System.out.println("exception");
                }
                System.out.println("Expected: exception");
        }
}

NegativeBalanceException.java

/**
 * This exception reports a negative initial balance on a bank account.
 */
public class NegativeBalanceException extends RuntimeException {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public NegativeBalanceException() {
        }

        public NegativeBalanceException(String message) {
                super(message);
        }
}

NegativeAmountException.java

/**
 * This exception reports a negative amount on with draw or deposite
 */
public class NegativeAmountException extends Exception {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public NegativeAmountException() {
        }

        public NegativeAmountException(String message) {
                super(message);
        }
        
}

InsufficientFundsException.java


/**
 * This exception reports a InsufficientFund on with draw 
 */
public class InsufficientFundsException extends Exception {


        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public InsufficientFundsException() {
        }

        public InsufficientFundsException(String message) {
                super(message);
        }
}

Output Of BankAccountTester2:

success
Expected: success
success
Expected: success
exception
Expected: exception
exception
Expected: exception

Related Solutions

java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a BankAccountconstructed from data input from the keyboard. Override ReadAccount in SavingsAccount to return an account that refers to a SavingsAccount that you construct, again initializing it with data from the keyboard. Similarly, implement ReadAccount in the CheckingAccount class. Use the following code to test your work. public static void testCode()         {             SavingsAccount savings = new SavingsAccount(100.00, 3.5);             SavingsAccount s = (SavingsAccount)savings.ReadAccount();...
using C++ Please create the class named BankAccount with the following properties below: // The BankAccount...
using C++ Please create the class named BankAccount with the following properties below: // The BankAccount class sets up a clients account (using name & id), and - keeps track of a user's available balance. - how many transactions (deposits and/or withdrawals) are made. public class BankAccount { private int id; private String name private double balance; private int numTransactions; // ** Please define method definitions for Accessors and Mutators functions below for the class private member variables string getName();...
You are to modify the Pez class so that all errors are handled by exceptions. The...
You are to modify the Pez class so that all errors are handled by exceptions. The constructor must be able to handle invalid parameters. The user should not be able to get a piece of candy when the Pez is empty. The user should not be able to put in more candy than the Pez can hold. I would like you to do 3 types of exceptions. One handled within the class itself, one handled by the calling method and...
*OBJECT ORIENTED PROGRAMMING* JAVA PROGRAMMING GOAL: will be able to throw and catch exceptions and create...
*OBJECT ORIENTED PROGRAMMING* JAVA PROGRAMMING GOAL: will be able to throw and catch exceptions and create multi-threaded programs. Part I Create a class called Animal that implements the Runnable interface. In the main method create 2 instances of the Animal class, one called rabbit and one called turtle. Make them "user" threads, as opposed to daemon threads. Some detail about the Animal class. It has instance variables, name, position, speed, and restMax. It has a static boolean winner. It starts...
*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs....
*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs. Part I Create a class called Animal that implements the Runnable interface. In the main method create 2 instances of the Animal class, one called rabbit and one called turtle. Make them "user" threads, as opposed to daemon threads. Some detail about the Animal class. It has instance variables, name, position, speed, and restMax. It has a static boolean winner. It starts a false....
Create a class BankAccount to hold at least the following data / information about a bank...
Create a class BankAccount to hold at least the following data / information about a bank account: Account balance Total number of deposits Total number of withdrawals Interest rate e.g., annual rate = 0.05 Service charges per month The class should have the following member functions: Constructor To set the required data. It may be parameterized or user’s input. depositAmount A virtual function used to accept an argument for the amount to be deposited. It should add the argument (amount)...
Write a program to create a bank account and to process transactions. Call this class bankAccount...
Write a program to create a bank account and to process transactions. Call this class bankAccount A bank account can only be given an initial balance when it is instantiated. By default, a new bank account should have a balance of 0. A bank account should have a public get method, but no public set method. A bank account should have a process method with a double parameter to perform deposits and withdrawals. A negative parameter represents a withdrawal. It...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of the account holder. a method, getBalance, that returns a double corresponding to the account balance. a method withdraw that accepts a double, and deducts the amount from the account balance. Write a class definition for a subclass, CheckingAccount, that contains: a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance). a constructor that...
2.     Modify assignment 1 solution code I posted to do the following: a.     Change car class to bankAccount...
2.     Modify assignment 1 solution code I posted to do the following: a.     Change car class to bankAccount class and TestCar class to TestBank class b.     Change mileage to balance c.     Change car info (make, model, color, year, fuel efficiency) to customer first and last name and account balance d.     Change add gas to deposit (without limit) e.     Change drive to withdraw cash f.  Change test car menu to the following Bank Account Menu choices 1 - Deposit 2 - Withdraw 3 - Display account info 4...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT