Java Bank Account Logic - java

I am trying to create a bank account class with few tools such as Balance, Deposit and withdrawal. I created super class and two sub class. One of the sub class(checking account) needs to charge a 10$ fee after 2 transactions.
I am having small trouble in the following program. It is a minor part of the program and I tried everything but I can not think of the solution. The problem is marked with star box comment in the code. The bank account (super Class) class is attached for your reference.
It is charging the transaction fee even though withdrawal is failed due to unavailability of enough balance. I understand why it is doing that but can someone suggest any solution?
//This is the sub Class "Checking Account"
public class CheckingAccount extends BankAccount
{
//Private Instance Variablea
private double dTransFee;
private int iFreeCheckPerMonth;
private int iNumChecks;
//Constructor
public CheckingAccount(String sName, int iAccountNumber)
{
super(sName, iAccountNumber);
dTransFee = 10;
iFreeCheckPerMonth = 2;
iNumChecks=0;
}
//Overriding method from the Bank Account Class
public boolean bWithdrawl (double dMoney)
{
if (iNumChecks<2)
{
super.bWithdrawl(dMoney);
iNumChecks++;
iFreeCheckPerMonth--;
}
else
{
/****************************
* I DON'T KNOW HOW I CAN MAKE STATEMENT SUCH AS
* IF BWITHDRAL IS FALSE(FAILS) DON'T TAKE OUT 10 FROM BALANCE.
***************************/
super.bWithdrawl(dMoney);
dBalance = dBalance- dTransFee;
iNumChecks++;
iFreeCheckPerMonth--;
}
return false;
}
//Prints how many checks are left
public int FreeChecksLeft ()
{
return iFreeCheckPerMonth;
}
//Prints how many checks have been used
public int CheckUsed ()
{
return iNumChecks;
}
}
//Super Class
/**************************************************************
*Name: BankAccount
*Input:Name and account number. Deposit and withdrawal amount for methods
*Output: None
*Description:
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
public class BankAccount
{
//Private Instance Variable
protected double dBalance;
protected int iAccountNum;
protected String sOwnerName;
//Constructor
public BankAccount (String sName, int iAccountNumber)
{
iAccountNum = iAccountNumber;
sOwnerName = sName;
}
/**************************************************************
*Name: deposit
*Input:amount of money
*Output: none
*Description: takes the amount of money and add the amount to the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for deposit
public void deposit(double dMoney)
{
dBalance += dMoney;
}
/**************************************************************
*Name: Withdrawal
*Input:amount of money
*Output: none
*Description: takes the amount of money and subtracts the amount from the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for Withdrawal
public boolean bWithdrawl (double dMoney)
{
if (dMoney <= dBalance)
{
dBalance -= dMoney;
}
return false;
}
//Method to get balance
public double getBalance()
{
return dBalance;
}
}
//Here is the tester for Checking Account
public class CheckingTester
{
public static void main(String[] args)
{
//Create Checking account
CheckingAccount ca1 = new CheckingAccount ("Apurva", 1000);
//Make deposit
ca1.deposit(500);
//Verify that it worked
System.out.println("After deposit the balance is: " + ca1.getBalance()+" Expected:500");
//Check #1
//Test a withdrawal
ca1.bWithdrawl(100);
//Verify that it worked
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 400");
//Checks the number of free checks available for use
ca1.FreeChecksLeft();
System.out.println("Number of Free Checks left are: "+ca1.FreeChecksLeft()+ " Expected 1");
//Check how many checks have been used
ca1.CheckUsed();
System.out.println("The number of check used are: "+ ca1.CheckUsed()+(" Expected 1"));
//Check #2
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 300");
//Check 3
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
//Check 4
ca1.bWithdrawl(200);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
}
}

Related

How to call methods from an extended class?

public class Account {
double currentBalance;
Account(double currentBalance) {
this.currentBalance = currentBalance;
}
double getBalance() {
return(this.currentBalance);
}
void deposit(double amount) {
this.currentBalance += amount;
}
void withdraw(double amount) {
this.currentBalance -= amount;
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance);
}
}
public class SavingsAccount extends Account {
double interestRate;
SavingsAccount(double interestRate, double amount) {
super(amount);
this.interestRate = interestRate;
}
void addInterest(double interestRate) {
this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
}
}
public class AccountTester {
public static void main(String[] args) {
System.out.println("Welcome to the COMP 251 BANK");
Account[] acc = new Account[10];
acc[0] = new Account (100000); // initial amount of 100k
System.out.println(acc[0].toString());
acc[0].deposit(50000); //deposit 50k
System.out.println("Current balance after depositing is: " + "$" + acc[0].getBalance());
acc[0].withdraw(10000);
System.out.println("Current balance after withdrawing is: " + "$" + acc[0].getBalance());
System.out.println();
System.out.println("CHECKING ACCOUNT");
acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
System.out.println(acc[1].toString());
acc[1].deposit(20000); //I dont know what to do about the chequeDeposit
System.out.println("Current balance after depositing is: " + "$" + acc[1].getBalance());
System.out.println();
System.out.println("SAVINGS ACCOUNT");
acc[2] = new SavingsAccount(10, 50000);
System.out.println(acc[2].toString());
acc[2].deposit(10000);
System.out.println("Current balance after depositing is: " + "$" + acc[2].getBalance());
acc[2].addInterest();
}
}
I'm still new to this so I'm sorry if this is a bad question but I tried playing around with each class and I still can't figure out how to use the addInterest method I created in the SavingsAccount class that extends the Account class. I tried SavingsAccount.addInterest but I get a static reference error. I thought acc[2].addInterest would work but it says its undefined for the type Account.
You need to cast acc[2] to SavingsAccount before calling the method.
((SavingsAccount) acc[2]).addInterest();
It is called downcasting and here is an explanation of it.
You're trying to invoke a child class' method, addInterest from a base class reference.
In fact, your array has been declared as an array of Account objects
Account[] acc = new Account[10];
This class does not offer the addIntereset method, even though your arr[2] contains a SavingAccount instance, Java in fact will only be able to know this at run-time. At compile time, your syntax must be compliant with the declared type (Account).
To work around this problem you have two solutions: creating a generic addInterest method in your base class which your child classes will override or cast your arr[2] to a SavingAccount instance.
With the first approach, you're offering an addInterest method from the base class, so whatever instance is going to call the method (an actual Account or a subtype), it will always be able to invoke it.
public class Account {
public void addInterest(double interest){
//Account implementation
}
}
public class SavingAccount {
#Overrride
public void addInterest(double interest){
//SavingAccount implementation
}
}
So, in your main you could type with no errors:
Account[] arr = new Account[10];
arr[0] = new Account();
arr[0].addInterest(5); //No error, dynamic dispatch will call Account's implementation
arr[1] = new SavingAccount();
arr[1].addInterest(10); //No error, dynamic dispatch will call SavingAccount's implementation
With the second approach instead, you need to make sure that what you're downcasting corresponds to the subtype of your casting.
//Randomly assigning to acc an Account instance or a SavingAccount instance
Account acc = Math.round(Math.random()) == 0 ? new Account() : new SavingAccount();
//Making sure to downcast acc to SavingAccount with the instanceof operator
if (acc instanceof SavingAccount){
SavingAccount savAcc = (SavingAccount) acc;
savAcc.addInterest(5);
}

How to print balance in a banking program (Java) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have created a Java program for banking, which allows the user to deposit funds, withdraw funds, and check their balance.
However, I would like to be able to print the convToString data (name, accNo, balance) whenever the getBalance() command is called. This would be much more effective than having to type System.out.println(JohnSmith.convToString()+"\n") each time I want to print the account information.
Any advice on how best to clean my code up and make this happen?
My full source code follows...
package week1src;
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount)
{
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a)
{
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Return a String containing all the information of the account based on account name input
--------------------*/
public String convToString( )
{
return("Account name: " + this.name + ", Account number: " + this.accNo + ", Available balance: " + "£" + this.balance);
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
}
else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
}
else { // returns an error message if withdrawal with put account balance below 0
System.err.println("Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
}
package week1src;
public class BankMain {
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1, 00); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£0)
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£15.00)
}
}
It can be achieved like this:
BankAccount.java:
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount) {
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a) {
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
} else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
} else { // returns an error message if withdrawal with put account balance below 0
System.err.println(
"Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
public void printAccountInfo() {
System.out.println(this);
}
#Override
public String toString() {
return "Account name: " + this.name + ", Account number: " + this.accNo
+ ", Available balance: " + "£" + this.balance;
}
}
BankMain.java:
package your.package.here;
public class BankMain{
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1,
0); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
JohnSmith.printAccountInfo();
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
JohnSmith.printAccountInfo();
}
}
It seems reasonable to create a separate reusable printing method, that will do all what you need. And instead of creating your convToString method, you can just override toString and then use it in a way that I've posted. This is built in java mechanism that do exactly what you need.
Tricky thing here is when you're calling System.out.println(this); default behavior is to call toString method on that object that you've passed to the System.out.println method.
And here is the magic happens, you just override toString, and then call System.out.println on your object instance. It will then take your instance and call your overrided toString on that.
Please, have a look.

Using a method from one class into another class

I am having trouble with my last method. I am informed that I have to use my adjust method from my BankAccount.class in my monthlyFee method in my bank class and I can not figure it out. I've tried multiple different things and can not get it to work. We need to adjust the balances of the accounts with the monthly fee.
Bank.java:33: error: method adjust in class BankAccount cannot be
applied to given types; BankAccount.adjust(); ^
required: double found: no arguments reason: actual and formal
argument lists differ in length 1 error
Bank.java:33: error: double cannot be dereferenced fee.adjust(); 1
error
Bank.java:33: error: cannot find symbol bank.BankAccount.adjust();
symbol: variable BankAccount location: variable bank of type
BankAccount[] 1 error
BankAccount.class
public class BankAccount {
String owner; // owner of account
int accountNumber; // integer account number
double balance = 0.0; // account balance
double amount; // adjusted amount to balance
String balanceFmt = "%.2f"; // string format for 2 decimal places
public BankAccount(String owner, int accountNumber) { //Constructor for the bank account
this.owner = owner;
this.accountNumber = accountNumber;
}
public double adjust(double amount) { //method to adjust balance
this.balance += amount;
return balance;
}
public String toString() { // method to print out account info
return owner + " owns the account " + accountNumber + " with the balance of $" + String.format(balanceFmt,balance);
}
public double getBalance() { // method to get balance of accounts
return balance;
}
}
Bank.class
public class Bank {
BankAccount bank[];
public Bank() { // constructor for making a 10 account array
bank = new BankAccount[10];
}
public void addAccount(BankAccount accounts) { // add account for giving numbers to accounts
for(int i = 0; i < bank.length; i++) {
if(bank[i] == null) {
bank[i] = accounts;
break;
}
}
}
BankAccount getAccount(int i) { //obtain account from BankAccount class
return bank[i];
}
public void printAccounts() { //prints out account statuses
for(int i = 0; i < bank.length; i++) {
if(bank[i] != null) {
System.out.println(bank[i]);
}
}
}
public void monthlyFee(double fee) { //monthly fee for bank accounts
for(int i = 0; i < bank.length; i++) {
if(bank[i] != null) {
} //I have tried BankAccount.adjust() and couldn't work, bank[i].adjust() nothing seems to work
}
}
}
BankTest.class
public class BankTest {
/*
* test - set up a bank and add accounts
*/
public static void main(String[] args) {
// Code to test Bank and BankAccount classes
int errors = 0;
double fee = -2.95;
Assignment assignment = new Assignment();
assignment.homework("Homework 2a");
System.out.println("\nCreate bank1");
Bank bank1 = new Bank();
System.out.println("\nOne account");
BankAccount bankAccount1 = new BankAccount("Joe Mac", 1234);
bankAccount1.adjust(1000.0);
bank1.addAccount(bankAccount1);
bank1.printAccounts();
System.out.println("\nTwo accounts");
BankAccount bankAccount2 = new BankAccount("Sally Ride", 2345);
bankAccount2.adjust(2000.0);
bank1.addAccount(bankAccount2);
bank1.printAccounts();
System.out.println("\nThree accounts");
BankAccount bankAccount3 = new BankAccount("Pat Armstrong", 3456);
bankAccount3.adjust(3000.0);
bank1.addAccount(bankAccount3);
bank1.printAccounts();
System.out.println("\nMonthly Fee");
bank1.monthlyFee(fee);
bank1.printAccounts();
System.out.println("\nErrors:");
if (bank1.getAccount(0).getBalance() != 997.05) {
errors += 1;
System.out.println("Balance for account at index 0 does not match $997.05");
}
if (bank1.getAccount(1).getBalance() != 1997.05)
{
errors += 1;
System.out.println("Balance for account at index 1 does not match $1997.05");
}
if (bank1.getAccount(2).getBalance() != 2997.05)
{
errors += 1;
System.out.println("Balance for account at index 2 does not match $2997.05");
}
if (errors == 0)
System.out.println("No errors found!!!");
}
}
Any help and guidance is much appreciated. Thank you.
Seems that you forgot to pass the fee parameter to adjust() method. Following code works perfectly fine
public void monthlyFee(double fee) { //monthly fee for bank accounts
for(int i = 0; i < bank.length; i++) {
if(bank[i] != null) {
System.out.println(bank[i].adjust(fee));
} //I have tried BankAccount.adjust() and couldn't work, bank[i].adjust() nothing seems to work
}
}
Create bank1
One account
Joe Mac owns the account 1234 with the balance of $1000.00
Two accounts
Joe Mac owns the account 1234 with the balance of $1000.00
Sally Ride owns the account 2345 with the balance of $2000.00
Three accounts
Joe Mac owns the account 1234 with the balance of $1000.00
Sally Ride owns the account 2345 with the balance of $2000.00
Pat Armstrong owns the account 3456 with the balance of $3000.00
Monthly Fee
997.05
1997.05
2997.05
Joe Mac owns the account 1234 with the balance of $997.05
Sally Ride owns the account 2345 with the balance of $1997.05
Pat Armstrong owns the account 3456 with the balance of $2997.05
Errors:
No errors found!!!
Simple: when you check your test code, you find that it passes a double value when that adjust() method is invoked!
Your other code (the one that leads to the error) seems to not pass any double when invoking that method!

BankAccount/SavingsAccount program withdraw method not working

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.

Java program doesn't add amounts correctly [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So I am still fairly new to java. I have written this but am not sure as to why when I run it, the amounts will not add to what is set in the client.
For example: I enter 500 as starting balance, if I hit deposit, and type 500, and then hit case 3, it should say 1000 but it still says 500. And then If i hit withdraw, it says I have -500.
Any ideas? Thanks
package bankaccount;
import java.util.Random;
import java.util.Scanner;
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount b1 = new BankAccount(cusName, accNo, balance);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
Money.amount = input.nextInt();
b1.getDeposit();
break;
case 2:
System.out.println("Current Account Balance=" + b1.getBalance());
System.out.print("Enter withdrawal amount:");
Money.amount = input.nextInt();
b1.getWithdraw();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
public class Money
{
public static int accountNumber, balance=0;
static int amount;
static String name;
public void setDeposit(int amount) {
balance = balance + amount;
}
public int getDeposit()
{
balance = balance + amount;
if (amount < 0) {
System.out.println("Invalid");
}
return 1;
}
public void setBalance(int b)
{
b = balance;
}
public int getBalance()
{
return balance;
}
public void setWithdraw(int amount) {
balance = balance - amount;
}
public int getWithdraw()
{
balance = balance - amount;
if (balance < amount)
{
System.out.println("Not enough funds.");
return 1;
}
else if (amount < 0) {
System.out.println("Invalid");
return 1;}
else
return 0;
}
import java.util.*;
public class BankAccount extends Money {
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
this.customerMoney = new Money();
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
void displayBalance() {
System.out.println("Balance:" + balance);
}
public Money getMoney(){
return this.customerMoney;
}
}
The biggest problem is at statement balance=0
public static int accountNumber, balance=0;
^^^^^^^^^
Every time when you are going to insert amount, your balance is ZERO.
You should have used setDeposit(input.nextInt())
In public void setBalance(int b), b = balance; should have been balance = b;
Also, your amount, balance variables should be Float instead of int as balance/amount can be 23434.22.
I would remove all the public static int variables that you are using. These are going to cause confusion because it's much harder to follow what their values are as the program executes. Best to encapsulate your logic into BankAccount using private variables and public methods to modify them.
I would, personally, eliminate the Money class from your code. It's just going to cause confusion and with your simplified logic is not required. Let's assume the account holds some arbitrary count of 'money' but there is no real-life money actually backing it up - (kind of like real life, it's just 'numbers on a screen' right?) - in this case we wouldn't need the Money class, just an int for our BankAccount's balance.
Without trying to make too many changes to your underlying functionality, I rewrote as the below two classes:
A BankAccount class:
package banking;
public class BankAccount {
/**
* The balance of this account. <br/>
* Assumes integer money (Floating point math is horrible and who really
* needs pesky pence or cents right?!)
*/
private int balance;
/**
* The account number
*/
private final int acctNum;
/**
* Name of the account holder
*/
private final String name;
/**
* Construct our basic account with an account number, account holder and
* starting balance.
*
* #param name
* #param accNo
* #param bal
*/
public BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
}
/**
* Make a deposit to this account by adding a fixed sum to the existing
* balance. <br/>
*
* #param amount
*/
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("You cannot deposit zero or less");
} else {
this.balance += amount;
}
}
/**
* Make a withdrawal from this account by subtracting a fixed amount from
* the existing balance. <br/>
*
* #param amount
*/
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient Funds");
} else if (amount <= 0) {
throw new IllegalArgumentException("You cannot withdraw zero or less");
} else {
balance -= amount;
}
}
/**
* Get the account holder name.
*
* #return
*/
public String getName() {
return name;
}
/**
* Get the current account balance.
*
* #return
*/
public int getBalance() {
return balance;
}
/**
* Get the account identifier for this account.
*
* #return
*/
public int getAcctNum() {
return acctNum;
}
/**
* Debug print method.
*/
public void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
}
And the main class:
package banking;
import java.util.Random;
import java.util.Scanner;
public class BankMain {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String customerName = input.nextLine();
Random randomGenerator = new Random();
int acctNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount acct = new BankAccount(customerName, acctNo, balance);
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
int menu;
do {
final int transaction;
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
transaction = input.nextInt();
acct.deposit(transaction);
break;
case 2:
System.out.println("Current Account Balance=" + acct.getBalance());
System.out.print("Enter withdrawal amount:");
transaction = input.nextInt();
try {
acct.withdraw(transaction);
} catch (IllegalArgumentException iaEx) {
System.out.println(iaEx.getMessage());
}
break;
case 3:
acct.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
This is still far from perfect, but I feel it's easier to follow for having the static variables and Money class removed.
You have many problems with the code e.g. none of your fields should be static, but the main one is that you have multiple duplicated fields.
e.g. In Money you have
public static int accountNumber, balance=0;
static int amount;
static String name;
and in BankAccount you have
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
which means you have multiple fields called name, balance and amount. Some of the code uses the first group of fields and some of the code uses the second. You also have a customerMoney which is not updated directly.
To avoid confusion I suggest you have each field be non-static and in only one place. Remove the customerMoney as you might be tempted to use it ;)

Categories