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 ;)
Related
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.
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'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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is a homework assignment. I need to consolidate the two accounts (acct2 and acct3) and produce a third one with the same name, different account number and $200. I also have to close the first two accounts. That is not really the issue though. I can get everything to work fine if I do not declare public static Account accountConsolidate(Account acct1, Account acct2) as a static method, and just create an object in the main. This does not work though because I am required to declare this method as static. Also, if I do declare it as static I can get the proper return value in the if(acct1.name.equalsIgnoreCase(acct2.name) && acct1.acctNum != acct2.acctNum) if I exclude the
`&& acct1.acctNum != acct2.acctNum
other wise it will return null ("These two accounts are not able to be consolidated. Please check the criteria again", not sure why.
Any help would be great. Thanks
import java.util.Random;
public class Account
{
private static int numAccounts = 0;
private double balance;
private static String name;
private static double acctNum;
static Random gen = new Random();
//-------------------------------------------------
//Constructor -- initializes balance, owner, and account number
//-------------------------------------------------
public Account(double initBal, String owner, double number)
{
balance = initBal;
name = owner;
acctNum = number;
numAccounts++;
}
public Account(double initBal, String owner)
{
balance = initBal;
name = owner;
acctNum = Math.abs(gen.nextDouble());
numAccounts++;
}
public Account(String owner)
{
balance = 0;
name = owner;
acctNum = Math.abs(gen.nextDouble());
numAccounts++;
}
//-------------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//-------------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
{
balance -= amount;
}
else
System.out.println("Insufficient funds");
}
public void withdraw(double amount, double fee)
{
if (balance >= amount)
{
balance -= amount;
balance -= fee;
}
else
System.out.println("Insufficient funds");
}
public String getName()
{
return name;
}
public double getNum()
{
return acctNum;
}
//-------------------------------------------------
// Adds deposit amount to balance.
//-------------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//-------------------------------------------------
// Returns balance.
//-------------------------------------------------
public double getBalance()
{
return balance;
}
// Static method to keep track of incrementing Account
public static int getNumAccounts()
{
return numAccounts;
}
// Close the account
public void close()
{
balance = 0;
name = "CLOSED";
numAccounts--;
}
// Consolidate accounts
public static Account accountConsolidate(Account acct1, Account acct2)
{
if(acct1.name.equalsIgnoreCase(acct2.name) && acct1.acctNum != acct2.acctNum)
{
Account Account2 = new Account(0, acct1.name);
Account2.balance = acct1.getBalance() + acct2.getBalance();
acctNum = Math.abs(gen.nextDouble());
acct1.close();
acct2.close();
return Account2;
}
else
{
System.out.println("These two accounts are not able to be consolidated. Please check the criteria again");
return null;
}
}
//-------------------------------------------------
// Returns a string containing the name, account number, and balance.
//-------------------------------------------------
public String toString()
{
return "Name:" + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
//************************************************************
//TestAccounts1
//A simple program to test the numAccts method of the
//Account class.
//************************************************************
import java.util.Scanner;
public class TestAccount1
{
public static void main(String[] args)
{
String name1;
String name2;
String name3;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the name for account 1: ");
name1 = scan.nextLine();
Account acct1 = new Account (100, name1);
System.out.println(acct1);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
System.out.print("Please enter the name for account 2: ");
name2 = scan.nextLine();
Account acct2 = new Account (100, name2);
System.out.println(acct2);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
System.out.print("Please enter the name for account 3: ");
name3 = scan.nextLine();
Account acct3 = new Account (100, name3);
System.out.println(acct3);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
acct1.close();
System.out.println("");
System.out.println("There are now " + Account.getNumAccounts() + " accounts");
System.out.println("Accounts consolidated");
System.out.println(Account.accountConsolidate(acct2, acct3));
}
}
Your account numbers are randomly generated but the accNum is static. So every account will have the created account number of the last account. So acct1.acctNum != acct2.acctNum will always be false.
Your account name is static as well, so each account will have the account name of the last created account.
After you changed this read your compiler errors. It will tell you what to do next. Think about which variables of which object you will modify. Like acctNum = Math.abs(gen.nextDouble()); will not set the account number of your consolidated account Account2.
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
+ ".");
}
}