1

I've been assigned to make a program from CS class to edit a previous program and include exceptions and such, and also serialize and de-serialize a file for its data. The program seems to work fine when it comes to depositing money, HOWEVER when I try to withdraw money, it just straight up doesn't work. And I'm not sure why even after going back through my other classes and tracing it to the source.

Here's my code.

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.

*/

public 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() {

 }

 public BankAccount(double bal, double rate)

 {

  try {

   deposit(bal);

  } catch (InvalidDeposit e) {

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

   balance = 0;

  }

  interestRate = rate;

  rate = 0.0;
  numDeposits = 0;
  numWithdrawals = 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;
  numDeposits = 0;
  numWithdrawals = 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 monthlyIR, monthlyI;

  monthlyIR = interestRate / 12;
  monthlyI = balance * monthlyIR;
  balance += monthlyI;

 }



 /**

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 -= getCharges();
  calcInterest();
  numDeposits = 0;
  numWithdrawals = 0;

 }

} //end BankAccount class

import java.io.Serializable;

/**

   This class holds the data for a savings account.

*/

public 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() //

 {
  status = false;
  if (getBalance() >= INACTIVE_AMT)

  {
   status = true;
  }

  return status;

 }



 /**

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() + "\tRate: " + getRate()

   +
   "\tCharges: " + getCharges() + "\tNo. of Deposits: " + getNumDeposits() +

   "\tNo. of Withdrawals: " + getNumWithdrawals() + "\nStatus: ";

  if (super.getBalance() < INACTIVE_AMT)

   msg += str1;

  else

   msg += str2;

  return msg;

 }

} //end SavingsAccount class

/**
   InvalidDeposit will extend the Exception
   class and allow the program to throw invalid
   data.
*/
public 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("Error: amount to deposit should be > 0 and < 10,000. ");
 }

}

/**

   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("Error: there is not enough money to withdraw.");

 }

}

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 = "savingsAccount.dat"; //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, rate, charge;



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


  amt = keyboard.nextDouble();
  while (amt < 0 || amt > 10000) {
   try {
    amt = keyboard.nextDouble();
   } catch (Exception e) {
    System.out.println(e.getMessage());
    System.out.print("Please re-enter: ");
    amt = keyboard.nextDouble();
   }
  }

  System.out.println("Please enter interest rate: ");
  rate = keyboard.nextDouble();

  System.out.println("Please enter monthly charge: ");
  charge = keyboard.nextDouble();


  SavingsAccount acct1 = new SavingsAccount(amt, rate, charge);


  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();

     boolean done1 = true;
     while (amt <= 0 || amt > 10000) {
      try {
       acct1.deposit(amt);

      } catch (InvalidDeposit e) {

       System.out.println(e.getMessage());
       System.out.println("Please re-enter: ");
       amt = keyboard.nextDouble();

      }
     }
     break;



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

     amt = keyboard.nextDouble();

     while (amt <= 0 || amt > acct1.getBalance() || amt > 10000) {

      try {

       acct1.withdraw(amt);


      } catch (InvalidWithdrawal e) {

       System.out.println(e.getMessage());
       System.out.println("Please re-enter: ");
       amt = keyboard.nextDouble();

      }
     }

     break;

    case 3:

     System.out.println(acct1);

     break;

    case 4:

     break;

    default:

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



   }

  }



  System.out.println("\n\nBefore monthly process.... \n" + acct1);

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

  acct1.monthlyProcess();

  System.out.println("\n\nAfter monthly process.... \n" + acct1);



  try {

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

   writeObj(acct1);



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

   acct1 = readObj();



   System.out.println("\nDeSerialized 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;

 }

}

I understand it might be hard to go through since it's lengthy, but what you're looking for is the "withdraw" method in the BankAccount and SavingsAccount classes. In my SavingsDemo class it should be removing money from the balance if it meets certain parameters, but even when it does meet those special rules, it won't remove money from the account.

2
  • 1
    Please format the code and reduce the number of extra blank lines. Also, what does not work mean? Is there an error? Please be specific. Also, use an IDE and add breakpoints to debug the code.
    – Andrew S
    Nov 21, 2018 at 16:14
  • Withdraw doesn't remove money from the balance. In a more specific code sense, it's supposed to subtract a certain amount, which is what the user specifies, from the total balance variable, but it doesn't.
    – Jacky
    Nov 21, 2018 at 16:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.