Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m struggling with a homework assignment for my java class. It takes Chapter 1

ID: 3858654 • Letter: I

Question

I'm struggling with a homework assignment for my java class. It takes Chapter 10 Programming Challenge 9 from "Starting out with Java" and modifies it to handle exceptions and be serialized. I'm really lost. I've writtend the custom exceptions, written a toString method and attempted to serialize it, but I don't really know if I've accomplished either of those last two. I've also been asked to create a menu, which I've never done. I've included my professor's instructions and the code I have. Any and all help would be appreciated.

Instructions:

Based on your Lab 5 (BankAccount and SavingsAccount claases), do the following:

If there are and problem and error in your BankAccount and SavingsAccount classes, fixed them.

You can remove the mutator, setBalance(), from the BankAccount class, because the deposit() method can replaced setBalance() (Set initial balance is deposit!)

Create user-defined exception classes for invalid deposit amount and withdrawal amount.

Throw the exceptions in the method where exception may occurs. The method which deposits money (including initializing the balance in the constructor) in the bank account, throws InvalidDepositAmount if deposit amount is less than or equal to 0, or greater than $10,000.

The method which withdraws money from the bank account, and throws InvalidWithdrawalAmount if withdrawal amount is less than or equal to 0, or greater than the current balance, or greater than $10,000.

Add the toString() method in the SavingsAccount class (The last output in the screen shot is from the toString() method).

Modify service classes to be serializable.

Create an application class:

Declare an object of the SavingsAccount class.

Create a menu, each one responds to each selection.

If the InvalidWithdrawalAmount or InvalidDepositAmount exception is thrown, handle it.

May recover from the exception to let the program continues, for example, for the initial balance. Look at the first screen shot provided below). You can study the PayrollDemo.java linked on Unit 10 main page and SalesReport2.java in the textbook (P715-716) (The java file is available in Unit 10 Source Code), as examples.

In the menu option, if an exception is thrown, no need to recover because the user can always to re-select the menu item to continue.

After the user exit the menu, call the method, monthlyProcess().

Save the objects to a binary file, savingsAccount.dat – object serialization.

Create a method called writeObj() to serialize SavingsAccount object. The parameter is the SavingsAccount object, and throw or handle exception(s), including exception(s) in Java and user-defined exceptions.

Read object data (accounts’ information) from the binary file, and display them on the screen - object de-serialization.

Create a method called readObj() to de-serialize SavingsAccount object, also display de-serialized results on the screen. Throw or handle exception(s), including exception(s) in Java and user-defined exceptions.

Test serialization and de-serialization methods in the main() method. If you throw exceptions in the called methods, you have to handle it in the main(). DO NOT THROW exception(s) in the main() method.

My code:

//**************************************************************
// Programmer: Jennifer Bailey
// CTP 150 - Section 876
// Lab 6
//*************************************************************

import java.text.DecimalFormat;
import java.io.*;
import java.util.Scanner;

/**
   InvalidDeposit will extend the Exception
   class and allow the program to throw invalid
   data.
*/
class InvalidDeposit extends Exception
{
   //No arg constructor
   public InvalidDeposit()
   {
super("Cannot deposit amounts less than or equal to $0 or greater than $10,000.");
   }
  
   /**
This constructor reports the attempted deposit amount.
@param amtD The amount to be deposited
   */
   public InvalidDeposit(double amtD)
   {
super("Invalid Deposit Amount: " + amtD);
   }

}

/**
   InvalidWithdrawal will extend the Exception class
   and allow the program to throw invalid data.
*/
class InvalidWithdrawal extends Exception
{
   //no arg constructor
   public InvalidWithdrawal()
   {
super("Cannot withdraw ammounts less than or equal to 0, " +
"amounts greater than the current balance, or amounts greater than $10,000.");
   }
  
   /**
The constructor reports the attempted withdrawal amount.
@param amtWD The amount intended to be withdrawn
   */
   public InvalidWithdrawal(double amtWD)
   {
super("Invalid Withdrawal Amount: ");
   }
}

/**
   The BankAccount class is an abstract class that holds
   general information about a bank account. Classes
   representing specific types of bank accounts should inherit
   from this class.
*/

abstract class BankAccount implements Serializable
{
   private double balance;
   private double interestRate; //annual interest rate
   private double serviceCharges;
   private int numDeposits;
   private int numWithdrawals;
  
   /**
This constructor sets the bank account's
balance and interest rate.
@param bal Sets the bank account's balance
@param rate Sets the bank account's interest rate
   */
   public BankAccount(double bal, double rate)
   {
balance = bal;
bal = 0.0;
interestRate = rate;
rate = 0.0;
   }
  
   /**
This constructor sets the bank account's
balance, interest rate, and service charges.
@param bal Sets the bank account's balance
@param rate Sets the bank account's interest rate
   */
   public BankAccount(double bal, double rate, double charges)
   {
balance = bal;
bal = 0.0;
interestRate = rate;
rate = 0.0;
serviceCharges = charges;
charges = 0.0;
   }

  
   /**
The setRate() method will set the interest
rate for the bank account.
@param rate Sets the interest rate for the account
   */
   public void setRate(double rate)
   {
interestRate = rate;
   }
  
   /**
The setCharges() method will set the value of
any service charges.
@param charges Sets the amount of service charges
   */
   public void setCharges(double charges)
   {
serviceCharges = charges;
   }
  
   /**
The getBalance() method will return the
bank account's balance when called.
@return balance Returns the bank account balance
   */
   public double getBalance()
   {
return balance;
   }
  
   /**
The getRate() method will return the
bank account's interest rate when called.
@return interestRate Returns the account interest rate
   */
   public double getRate()
   {
return interestRate;
   }
  
   /**
The getCharges() method will return the
bank account's service charge amount.
@return serviceCharges Returns the service charge amount
   */
   public double getCharges()
   {
return serviceCharges;
   }
  
   /**
The getNumDeposits() method pulls the number
of deposits totaled in the deposit method and
returns the integer value.
@return numD Returns the total number of deposits made
   */
   public int getNumDeposits()
   {
return numDeposits;
   }

   /**
The deposit() method accepts an entered deposit
amount and adds it to the balance. It also totals
how many deposits are made.
@return balance Returns the new balance amount
after deposits have been made.
@exception InvalidDeposit When an invalid deposit is given.
   */
   public void deposit(double amtD) throws InvalidDeposit
   {
balance = amtD;
if(amtD <= 0 || amtD > 10000)
   throw new InvalidDeposit(amtD);
else
   balance = balance + amtD;
   numDeposits++;
   }
  
   /**
The getNumWithdrawal() method pulls the number
of withdrawals totaled in the withdraw method and
returns the integer value.
@return numWithdrawals Returns the total number of withdrawals made
   */
  
   public int getNumWithdrawals()
   {
return numWithdrawals;
   }
  
   /**
The withdraw() method accepts an entered withdrawal amount
and subtracts it from the balance. It also keeps a running
total of how many withdrawals are made.
@return balance Returns the new account balance after
withdrawals have been made.
@exception InvalidWithdrawal When an invalid withdrawal is attempted
   */
   public void withdraw(double amtW) throws InvalidWithdrawal
   {
if(amtW <= 0 || amtW > 10000 || amtW > balance)
   throw new InvalidWithdrawal(amtW);
else
   balance = balance - amtW;
   numWithdrawals++;
   }

   /**
The calcInterest() method calculates the interest
amount earned each month and adds it to the balance.
@return balance The new balance is returned after
the interest amount has be calculated and added to it.
   */
   public void calcInterest()
   {
double monRate; //interest rate per month
double monInterest; //the amount of interest paid per month

monRate = interestRate/12;
monInterest = balance * monRate;
balance = balance + monInterest;
   }
  
   /**
The monthlyProcess() method will calculate the balance
after subtracting the amount of service charges.
@return balance Returns the balance amount after
service charges have been subtracted.
   */
   public void monthlyProcess()
   {
balance = balance - getCharges();
calcInterest();
serviceCharges = 0;
numDeposits = 0;
numWithdrawals = 0;
   }
} //end BankAccount class


/**
   This class holds the data for a savings account.
*/
class SavingsAccount extends BankAccount implements Serializable
{
   public final static double INACTIVE_AMT = 25.00;
   private boolean status;
  
  
   /**
This Constructor sets the account balance and
interest rate for the savings account.
@param acctBal Sets the account balance
@param interest Sets the account interest rate
   */
   public SavingsAccount(double acctBal, double interest)
   {
super(acctBal, interest);
acctBal = super.getBalance();
   }
  
   /**
This Constructor sets the account balance and
interest rate for the savings account.
@param acctBal Sets the account balance
@param interest Sets the account interest rate
   */
   public SavingsAccount(double acctBal, double interest, double acctCharges)
   {
super(acctBal, interest, acctCharges);
acctBal = super.getBalance();
   }
  
   /**
The getStatus() method will return true or
false for the activity status of the savings account.
@return status Returns the status of the savings account
   */
   public boolean getStatus()
   {
return status;
   }
  
   /**
The checkStatus() method checks to see if the
account balance is more or less than $25. If more than,
the account is active. If less than, the account is in active.
@return status Returns the activity status for the account.
   */
   public boolean checkStatus() //
   {
if(getBalance() >= INACTIVE_AMT)
   return true;
return false;
   }
  
   /**
The withdraw() method checks the account status and
returns the account balance after a withdrawal.
@param acctBal Sets the account balance
@param amtWD Sets the withdrawal amount
@return super.withdraw(amtWD) returns the account
a balance after the calculations done in the superclass.
@exception InvalidDeposit When an invalid deposit is given.
   */
   public void withdraw(double amtWD) throws InvalidWithdrawal
   {
  
   if(checkStatus() == true)
   super.withdraw(amtWD);
   checkStatus();
   if(checkStatus() == false)
System.out.println("The withdrawal can't be made. The account is inacitve.");
   }
  
   /**
The deposit() method checks the account status and
returns the account balance after a deposit.
@param acctBal Sets the account balance
@param amtD Sets the deposit amount
@return super.deposit(amtD) returns the account
a balance after the calculations done in the superclass.
@exception InvalidWithdrawal When an invalid withdrawal is attempted.
   */
   public void deposit(double amtD)throws InvalidDeposit
   {
if((getStatus() == false) && (getBalance() + amtD > INACTIVE_AMT))
   super.deposit(amtD);
   }
  
   public void monthlyProcess()
   {
double accountCharges = 0.0;
if(super.getNumWithdrawals() > 4)
   accountCharges = ((getNumWithdrawals() - 4) * 1) + super.getCharges();
else
   accountCharges = 0 + super.getCharges();
  
super.setCharges(accountCharges);

super.monthlyProcess();
checkStatus();
if(checkStatus() == false)
   System.out.println("The balance is less $25. The account is inactive.");
   }
  
   /**
toString method
@return A string representation of an object.
   */
   public String toString()
   {
String str1 = "The account is inactive!";
String str2 = "The account is active.";
String msg = " ";

System.out.println("Read data from the file..");
System.out.println("Balance: " + super.getBalance());
if(super.getBalance() < INACTIVE_AMT)
   msg = str1;
else
   msg = str2;
return msg;
   }

} //end SavingsAccount class

/**
   The following application will demonstrate the
   exceptions and service classes stated above.
*/

public class SavingsDemo
{
   public static void main(String[] args)
   {
Scanner keyboard = new Scanner(System.in);
int start = 0;
SavingsAccount acct1 = new SavingsAccount(15000.00, .05, 2.5);

System.out.println("Enter 1 to start: ");
start = keyboard.nextInt();

if(start == 1)
   System.out.println("Please enter the initial balance: ");
  
   }
}

Explanation / Answer

Given below are the modified files with output .Please rate the answer if it helped. Thank you.

InvalidWithdrawal

/**

   InvalidWithdrawal will extend the Exception class

   and allow the program to throw invalid data.

*/

class InvalidWithdrawal extends Exception

{

   //no arg constructor

   public InvalidWithdrawal()

   {

super("Cannot withdraw ammounts less than or equal to 0, " +

"amounts greater than the current balance, or amounts greater than $10,000.");

   }

  

   /**

The constructor reports the attempted withdrawal amount.

@param amtWD The amount intended to be withdrawn

   */

   public InvalidWithdrawal(double amtWD)

   {

super("Invalid Withdrawal Amount: " + amtWD);

   }

}

BankAccount

import java.io.Serializable;

/**

   The BankAccount class is an abstract class that holds

   general information about a bank account. Classes

   representing specific types of bank accounts should inherit

   from this class.

*/

abstract class BankAccount implements Serializable

{

   private double balance;

   private double interestRate; //annual interest rate

   private double serviceCharges;

   private int numDeposits;

   private int numWithdrawals;

  

   public BankAccount()

   {

     

   }

   /**

This constructor sets the bank account's

balance and interest rate.

@param bal Sets the bank account's balance

@param rate Sets the bank account's interest rate

   */

   public BankAccount(double bal, double rate)

   {

try {

       deposit(bal);

   } catch (InvalidDeposit e) {

       System.out.println(e.getMessage());

       balance = 0;

   }

interestRate = rate;

rate = 0.0;

   }

  

   /**

This constructor sets the bank account's

balance, interest rate, and service charges.

@param bal Sets the bank account's balance

@param rate Sets the bank account's interest rate

   */

   public BankAccount(double bal, double rate, double charges)

   {

try {

       deposit(bal);

   } catch (InvalidDeposit e) {

       System.out.println(e.getMessage());

       balance = 0;

   }

interestRate = rate;

rate = 0.0;

serviceCharges = charges;

charges = 0.0;

   }

  

   /**

The setRate() method will set the interest

rate for the bank account.

@param rate Sets the interest rate for the account

   */

   public void setRate(double rate)

   {

interestRate = rate;

   }

  

   /**

The setCharges() method will set the value of

any service charges.

@param charges Sets the amount of service charges

   */

   public void setCharges(double charges)

   {

serviceCharges = charges;

   }

  

   /**

The getBalance() method will return the

bank account's balance when called.

@return balance Returns the bank account balance

   */

   public double getBalance()

   {

return balance;

   }

  

   /**

The getRate() method will return the

bank account's interest rate when called.

@return interestRate Returns the account interest rate

   */

   public double getRate()

   {

return interestRate;

   }

  

   /**

The getCharges() method will return the

bank account's service charge amount.

@return serviceCharges Returns the service charge amount

   */

   public double getCharges()

   {

return serviceCharges;

   }

  

   /**

The getNumDeposits() method pulls the number

of deposits totaled in the deposit method and

returns the integer value.

@return numD Returns the total number of deposits made

   */

   public int getNumDeposits()

   {

return numDeposits;

   }

   /**

The deposit() method accepts an entered deposit

amount and adds it to the balance. It also totals

how many deposits are made.

@return balance Returns the new balance amount

after deposits have been made.

@exception InvalidDeposit When an invalid deposit is given.

   */

   public void deposit(double amtD) throws InvalidDeposit

   {

if(amtD <= 0 || amtD > 10000)

   throw new InvalidDeposit(amtD);

else

{

   balance = balance + amtD;

   numDeposits++;

}

   }

  

   /**

The getNumWithdrawal() method pulls the number

of withdrawals totaled in the withdraw method and

returns the integer value.

@return numWithdrawals Returns the total number of withdrawals made

   */

  

   public int getNumWithdrawals()

   {

return numWithdrawals;

   }

  

   /**

The withdraw() method accepts an entered withdrawal amount

and subtracts it from the balance. It also keeps a running

total of how many withdrawals are made.

@return balance Returns the new account balance after

withdrawals have been made.

@exception InvalidWithdrawal When an invalid withdrawal is attempted

   */

   public void withdraw(double amtW) throws InvalidWithdrawal

   {

if(amtW <= 0 || amtW > 10000 || amtW > balance)

   throw new InvalidWithdrawal(amtW);

else

{

   balance = balance - amtW;

   numWithdrawals++;

}

   }

   /**

The calcInterest() method calculates the interest

amount earned each month and adds it to the balance.

@return balance The new balance is returned after

the interest amount has be calculated and added to it.

   */

   public void calcInterest()

   {

double monRate; //interest rate per month

double monInterest; //the amount of interest paid per month

monRate = interestRate/12;

monInterest = balance * monRate;

balance = balance + monInterest;

   }

  

   /**

The monthlyProcess() method will calculate the balance

after subtracting the amount of service charges.

@return balance Returns the balance amount after

service charges have been subtracted.

   */

   public void monthlyProcess()

   {

balance = balance - getCharges();

calcInterest();

serviceCharges = 0;

numDeposits = 0;

numWithdrawals = 0;

   }

} //end BankAccount class


SavingsAccount

import java.io.Serializable;

/**

   This class holds the data for a savings account.

*/

class SavingsAccount extends BankAccount implements Serializable

{

   public final static double INACTIVE_AMT = 25.00;

   private boolean status;

  

   public SavingsAccount()

   {

     

   }

   /**

This Constructor sets the account balance and

interest rate for the savings account.

@param acctBal Sets the account balance

@param interest Sets the account interest rate

   */

   public SavingsAccount(double acctBal, double interest)

   {

super(acctBal, interest);

acctBal = super.getBalance();

   }

  

   /**

This Constructor sets the account balance and

interest rate for the savings account.

@param acctBal Sets the account balance

@param interest Sets the account interest rate

   */

   public SavingsAccount(double acctBal, double interest, double acctCharges)

   {

super(acctBal, interest, acctCharges);

acctBal = super.getBalance();

   }

  

   /**

The getStatus() method will return true or

false for the activity status of the savings account.

@return status Returns the status of the savings account

   */

   public boolean getStatus()

   {

return status;

   }

  

   /**

The checkStatus() method checks to see if the

account balance is more or less than $25. If more than,

the account is active. If less than, the account is in active.

@return status Returns the activity status for the account.

   */

   public boolean checkStatus() //

   {

if(getBalance() >= INACTIVE_AMT)

   return true;

return false;

   }

  

   /**

The withdraw() method checks the account status and

returns the account balance after a withdrawal.

@param acctBal Sets the account balance

@param amtWD Sets the withdrawal amount

@return super.withdraw(amtWD) returns the account

a balance after the calculations done in the superclass.

@exception InvalidDeposit When an invalid deposit is given.

   */

   public void withdraw(double amtWD) throws InvalidWithdrawal

   {

  

   if(checkStatus() == true)

   super.withdraw(amtWD);

   checkStatus();

   if(checkStatus() == false)

System.out.println("The withdrawal can't be made. The account is inacitve.");

   }

  

   /**

The deposit() method checks the account status and

returns the account balance after a deposit.

@param acctBal Sets the account balance

@param amtD Sets the deposit amount

@return super.deposit(amtD) returns the account

a balance after the calculations done in the superclass.

@exception InvalidWithdrawal When an invalid withdrawal is attempted.

   */

   public void deposit(double amtD)throws InvalidDeposit

   {

if((getStatus() == false) && (getBalance() + amtD > INACTIVE_AMT))

   super.deposit(amtD);

   }

  

   public void monthlyProcess()

   {

double accountCharges = 0.0;

if(super.getNumWithdrawals() > 4)

   accountCharges = ((getNumWithdrawals() - 4) * 1) + super.getCharges();

else

   accountCharges = 0 + super.getCharges();

  

super.setCharges(accountCharges);

super.monthlyProcess();

checkStatus();

if(checkStatus() == false)

   System.out.println("The balance is less $25. The account is inactive.");

   }

  

   /**

toString method

@return A string representation of an object.

   */

   public String toString()

   {

String str1 = "The account is inactive!";

String str2 = "The account is active.";

String msg = " ";

msg = "Balance: " + getBalance() + " Rate: " + getRate()

   +" Charges: " + getCharges() + " No. of Deposits: " + getNumDeposits() +

   " No. of Withdrawals: " + getNumWithdrawals() + " Status: ";

if(super.getBalance() < INACTIVE_AMT)

   msg += str1;

else

   msg += str2;

return msg;

   }

} //end SavingsAccount class

SavingsDemo

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.Scanner;

/**

   The following application will demonstrate the

   exceptions and service classes stated above.

*/

public class SavingsDemo

{

  

   private static String filename = "accobj.ser"; //name of the file where the object will be serialized

   public static void main(String[] args)

   {

Scanner keyboard = new Scanner(System.in);

int choice = 0;

double amt;

  

System.out.print("Please enter the initial balance: ");

amt = keyboard.nextDouble();

SavingsAccount acct1 = new SavingsAccount(amt, .05, 2.5);

  

while(choice != 4)

{

      System.out.println("1. Deposit");

      System.out.println("2. Withdraw");

      System.out.println("3. View account");

      System.out.println("4. Exit");

      System.out.print("Enter your choice: ");

      choice = keyboard.nextInt();

      

      switch(choice)

      {

         case 1: System.out.print("Enter deposit amount: ");

                 amt = keyboard.nextDouble();

                   try {

                       acct1.deposit(amt);

                       System.out.println("Amount deposited successfully");

                   } catch (InvalidDeposit e) {

                       System.out.println(e.getMessage());

                   }

                   break;

          

         case 2: System.out.print("Enter withdrawal amount: ");

                     amt = keyboard.nextDouble();

                   try {

                       acct1.withdraw(amt);

                       System.out.println("Amount withdrawn successfully");

                   } catch (InvalidWithdrawal e) {

                       System.out.println(e.getMessage());

                   }

                   break;

         case 3:

             System.out.println(acct1);

               break;

         case 4:

             break;

         default:

             System.out.println("Invalid menu choice!");

          

      }

}

  

System.out.println(" Before monthly process.... " + acct1);

System.out.println("Performing monthly process...");

acct1.monthlyProcess();

System.out.println(" After monthly process.... " + acct1);

  

try {

      System.out.println(" Serializing object to file " + filename);

      writeObj(acct1);

      

      System.out.println(" DeSerializing object from file " + filename);

      acct1 = readObj();

      

      System.out.println(" DeSerialized object details are ");

      System.out.println (acct1);

      

       } catch (IOException e) {

           System.out.println(e.getMessage());

       }

  

   }

  

   private static void writeObj(SavingsAccount acc) throws IOException

   {

   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));

   oos.writeObject(acc);

   oos.close();

   }

   private static SavingsAccount readObj() throws IOException

   {

   ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));

   SavingsAccount acc = null;

   try {

       acc = (SavingsAccount)(ois.readObject());

         

       } catch (ClassNotFoundException e) {

           System.out.println(e.getMessage());

       }

   ois.close();

   return acc;

   }

}


output

Please enter the initial balance: 15000

Invalid Deposit Amount: 15000.0

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 3

Balance: 0.0   Rate: 0.05   Charges: 2.5   No. of Deposits: 0   No. of Withdrawals: 0

Status: The account is inactive!

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 1

Enter deposit amount: 1000

Amount deposited successfully

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 1

Enter deposit amount: 200

Amount deposited successfully

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 3

Balance: 1200.0   Rate: 0.05   Charges: 2.5   No. of Deposits: 2   No. of Withdrawals: 0

Status: The account is active.

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 2

Enter withdrawal amount: 2500

Invalid Withdrawal Amount: 2500.0

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 2

Enter withdrawal amount: 500

Amount withdrawn successfully

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 3

Balance: 700.0   Rate: 0.05   Charges: 2.5   No. of Deposits: 2   No. of Withdrawals: 1

Status: The account is active.

1. Deposit

2. Withdraw

3. View account

4. Exit

Enter your choice: 4

Before monthly process....

Balance: 700.0   Rate: 0.05   Charges: 2.5   No. of Deposits: 2   No. of Withdrawals: 1

Status: The account is active.

Performing monthly process...

After monthly process....

Balance: 700.40625   Rate: 0.05   Charges: 0.0   No. of Deposits: 0   No. of Withdrawals: 0

Status: The account is active.

Serializing object to file accobj.ser

DeSerializing object from file accobj.ser

DeSerialized object details are

Balance: 700.40625   Rate: 0.05   Charges: 0.0   No. of Deposits: 0   No. of Withdrawals: 0

Status: The account is active.