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.
Related
I am currently taking lessons in OOP java. In my code below i am implementing polymorphism at run time as well as inheritance. I am creating a constant named "balance".
The goal of this program is to create a class called Account and extend the class with two types of classes called SBaccount and current.
The common attributes shared with Account is name, number and amount. So far i have a working code but its not quite doing what I want yet.
I want to be able to ask the user for the type of account that needs to be created, once the user specifies the type I want to validate the user input. I also want for example if a user deposits xx amount, that amount should be added to the balance and then stored. I want in the "withdraw" method, when the user makes a withdrawal it should be taken from the balance.
My code:
import java.util.Scanner;
abstract class Account{
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
public Account(){
}
int deposit(int i) {
return i;
}
void withdrawal(int i){
}
}
final class sbaccount extends Account {
public sbaccount() {
// TODO Auto-generated constructor stub
}
int deposit (int money){
bal = money + balance;
System.out.println("You have deposited :$"+money );
System.out.println("Your Account balance is now :"+bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
final class current extends Account {
public current() {
}
int deposit ( int money){
bal = money + balance;
System.out.println("You have deposited :$"+money);
System.out.println("Your Account balance is now :"+ bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
public class oopassignment {
public static void main(String[] args) {
String type;
Scanner input = new Scanner (System.in);
System.out.println("What type of account do you want to create? :");
type=input.nextLine();
Account sb;
sb = new sbaccount();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
So you can do the following task through class.newInstance() method.
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
The class c will load the class according to the argument passed. And object will be created through casting (required as initially the the object is of type "Class").
So finally your code will be (some modification is done) :
import java.util.Scanner;
abstract class Account {
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
abstract int deposit(int i);
abstract void withdrawal(int i);
}
final class sbaccount extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
final class current extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
public class oopassignment {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
// The only valid optios are : sbaccount & current.
// If any other class name is inputted. It will show exception
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
Let me know if any modification is needed to answer.
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");
}
}
The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have an assignment for class and it's to go over inheritance and overloading and overriding methods. I think I did everything asked for in the instructions. However, I am a little confused about overloading and if I did it correctly. Actually not really sure how it works so I don't know if I did it all. So you do not have to read through the directions, my main question refers to, the directions that ask "Create two overloaded deposit methods in Account class such that one of them takes an integer value as the input parameter and the second one takes a double value as the input parameter." and I am not sure I did it correctly.
THANKS FOR ANY HELP!!!
Scott
Instructions available upon request.
Here is what I have....
ACCOUNT CLASS (super class)
//Account class
public class Account {
//create data fields
Scanner scan = new Scanner(System.in);
protected int id = 0;
protected double balance = 0;
protected double annualInterestRate = 0;
protected Date dateCreated;
public Account() {
dateCreated = new Date();
}
//constructor for account w/ with id and balance args.
public Account(int newID, double newBalance, double interestRate) {
dateCreated = new Date();
id = newID;
balance = newBalance;
annualInterestRate = interestRate;
}//end account method
//setter for account ID
public int setID(int newID) {
return id = newID;
}//end setID
//getter for account ID
public int getID() {
return id;
}//end getID
//setter for account balance
public void setBalance(double newBalance) {
balance = newBalance;
}//end setBalance
//getter for account balance
public double getbalance() {
return balance;
}//end method getBalance
//setter for accounts annual interest rate
public void setAnnualInterestrate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}//end setAnnualInterestRate
//getter for accounts annual interest rate
public double getAnnualInterestRate() {
return annualInterestRate;
}//end getAnnualInterestRate
//getter for date account was created
public Date getDateCreated() {
return dateCreated;
}//end getDateCreated
//calls the annual interest rate and divides by 12 to get the monthly rate
public double getMonthlyInterestRate() {
return (annualInterestRate) / 12;
}//end getMonthlyInterestRate
//method to make a withdrawal from account
public double withdraw(double withdrawAmount) {
balance -= withdrawAmount;
return withdrawAmount;
}
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
}
SAVINGS ACCOUNT CLASS
public class SavingAccount extends Account {
public SavingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double withdraw(double withdrawAmount){
if(balance >= withdrawAmount){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("You cannot be overdraw your Savings Account! \nThe max you will be allowed to withdraw is: " + balance + "\n");
setBalance(0);
return balance;
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
CHECKING ACCOUNT CLASS
public class CheckingAccount extends Account{
double overDraft = 5000;
public CheckingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double getOverdraft() {
return overDraft;
}
public void setOverdraft(double overdraft) {
overDraft = 5000;
}
public double withdraw(double withdrawAmount){
double balance = getbalance();
if(balance - withdrawAmount >= -overDraft){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("reach overdraf limit!");
setBalance(-overDraft);
return overDraft + getbalance();
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
TESTACCOUNT CLASS
import java.util.*;
public class TestAccount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int accID = 0;
double balance = 0;
double intRate = 0;
double withDraw = 0;
double Deposit = 0;
//savings account
System.out.println("Please enter the ID of the Savings Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Savings Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Savings Account: ");
intRate = scan.nextDouble();
scan.nextLine();
SavingAccount s = new SavingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Savings Account: ");
withDraw = scan.nextDouble();
s.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Savings Account: ");
Deposit = scan.nextDouble();
s.deposit(Deposit);
System.out.println("\nSavings Account Status:\n" + s);
//Checking account
System.out.println("\nPlease enter the ID of the Checking Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Checking Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Checking Account: ");
intRate = scan.nextDouble();
scan.nextLine();
CheckingAccount c = new CheckingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Checking Account: ");
withDraw = scan.nextDouble();
c.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Checking Account: ");
Deposit = scan.nextDouble();
c.deposit(Deposit);
System.out.println("\nChecking Account Status:\n" + c);
}
}
Also, is there anything else you would change to make the program better?
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
Yes, these are overloaded methods. You did it correctly.
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 ;)