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.
Related
I am trying to outline an ArrayList of bank accounts in my main method, call a search on all accounts in that list, if the account is there...deposit money. Actual specs of program:
Design and implement a program that performs in the following way:
• When the program starts, two bank accounts are created, using names and
numbers which are written into the code;
• The user is then asked to enter an account number, followed by an amount to
deposit in that account;
• The balance of the appropriate account is then updated accordingly—or if an
incorrect account number was entered a message to this effect is displayed; this search portion of the spec is whats throwing me.
• The user is then asked if he or she wishes to make more deposits;
• If the user answers does wish to make more deposits, the process continues;
• If the user does not wish to make more deposits, then details of both accounts
(account number, account name and balance) are displayed.
When i run the code it returns output for when the account is not found... clearly the accounts I am defining arent being transferred to the ArrayList as im expecting.
BankAccount class:
import java.util.ArrayList;
public class BankAccount {
// the attributes
private String accountNumber;
private String accountName;
private double balance;
private char choice;
//Notice the static attribute
private static double interestRate;
// the methods
// the constructor
public BankAccount(String numberIn, String nameIn)
{
accountNumber = numberIn;
accountName = nameIn;
balance = 0;
}
// methods to read the attributes
public String getAccountName()
{
return accountName;
}
public String getAccountNumber()
{
return accountNumber;
}
public double getBalance()
{
return balance;
}
// methods to deposit and withdraw money
public void deposit(double amountIn)
{
balance = balance + amountIn;
}
public void withdraw(double amountIn)
{
if (amountIn > balance)
{
System.out.println("Sorry, there is an insufficient amount in your account to complete this withdrawal");
}
else
{
System.out.println("Withdrawal Successful");
balance = balance - amountIn;
}
}
public void setInterestRate(double rateIn)
{
interestRate = rateIn;
}
public double getInterestRate()
{
return interestRate;
}
public void addInterest()
{
balance = balance + (balance *interestRate)/100;
}
}
Bank Class:
import java.util.ArrayList;
public class Bank {
ArrayList<BankAccount> list = new ArrayList<>();
// helper method to find the index of a specified account
private int search(String accountNumberIn)
{
for(int i = 0; i <= list.size() - 1; i++)
{
BankAccount tempAccount = list.get(i); // find the account at index i
String tempNumber = tempAccount.getAccountNumber(); // get account number
if(tempNumber.equals(accountNumberIn)) // if this is the account we are looking for
{
return i; // return the index
}
}
return -999;
}
// return the total number of items
public int getTotal()
{
return list.size();
}
// return an account with a particular account number
public BankAccount getItem(String accountNumberIn)
{
int index = search(accountNumberIn);
if(index != -999) // check that account exists
{
return list.get(index);
}
else
{
return null; // no such account
}
}
// add an item to the list
public boolean addAccount(String accountNumberIn, String nameIn)
{
if(search(accountNumberIn) == -999) // check that account does not already exist
{
list.add(new BankAccount(accountNumberIn, nameIn)); // add new account
return true;
}
return false;
}
// deposit money in a specified account
public boolean depositMoney(String accountNumberIn, double amountIn)
{
BankAccount acc = getItem(accountNumberIn);
if(acc != null)
{
acc.deposit(amountIn);
return true; // indicate success
}
else
{
return false; // indicate failure
}
}
// withdraw money from a specified account
public boolean withdrawMoney(String accountNumberIn, double amountIn)
{
BankAccount acc = getItem(accountNumberIn);
if(acc != null && acc.getBalance() >= amountIn)
{
acc.withdraw(amountIn);
return true; // indicate success
}
else
{
return false; // indicate failure
}
}
// remove an account
public boolean removeAccount(String accountNumberIn)
{
int index = search(accountNumberIn); // find index of account
if(index != -999) // if account exists account
{
list.remove(index);
return true; // remove was successful
}
else
{
return false; // remove was unsuccessful
}
}
}
And finally the testing class with main method:
import java.util.ArrayList;
public class BankAccountTester {
public static void main(String args[])
{
Bank myBank = new Bank();
ArrayList<BankAccount> accountList = new ArrayList<>();
accountList.add(new BankAccount("123","Susan Richards"));
accountList.add(new BankAccount("44567109","Delroy Jacobs"));
accountList.add(new BankAccount("46376205","Sumana Khan"));
char choice;
do {
System.out.println("Please enter your account number:");
String myAcc = EasyScanner.nextString();
BankAccount account = myBank.getItem(myAcc);
System.out.println("Please enter an amount to deposit: ");
double depIn = EasyScanner.nextDouble();
boolean found = myBank.depositMoney(myAcc, depIn);
if (found)
{
System.out.println("Deposit made");
} else
{
System.out.println("Invalid account number"); //this is running everytime
}
System.out.println("Would you like to deposit again? (y/n)");
choice = EasyScanner.nextChar();
} while (choice == 'y' || choice == 'Y');
System.out.println("Account Details..... \n");
for(BankAccount item : accountList)
{
System.out.println("Account number: " + item.getAccountNumber());
System.out.println("Account name: " + item.getAccountName());
System.out.println("Current balance: " + item.getBalance());
System.out.println();
}
}
}
The output i get is as follows:
Please enter your account number:
123
Please enter an amount to deposit:
10
**Invalid account number**
Would you like to deposit again? (y/n)
I cant figure out why the account number isnt being picked up, although I can guess that the ArrayList being searched doesnt hold the account information that has been input.
Any help would be appreciated!
You have to add to accountList in myBank not in main.
myBank.addAccount ("123","Susan Richards"));
myBank.addAccount ("44567109","Delroy Jacobs"));
myBank.addAccount ("46376205","Sumana Khan"));
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 am trying to create and execute a method which allows the user to choose an account from which and an account to which the user wants to transfer an amount, which the user also chooses. But, I don't know how to get user input asking from and to which class they want to transfer funds to.
I've tried using the Scanner method but I can't get it to work.
Here is the code, it's the same as the code beneath this but this is easier to view imo: https://gist.github.com/KamronKelley/32d9a40c285e501f64cf73fa28bf87b5
package banking;
public class Account {
String name;
double balance;
public Account() {
name = "";
balance = 0.0;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void addFunds(double addedAmount) {
balance = balance + addedAmount;
}
public void withdraw(double withdrawnAmount) {
balance = balance - withdrawnAmount;
}
public void transfer(double amount, Account from, Account to) { //here is the transfer method, if i can improve this or alter it in order to make it easier to run using user input from the main file, let me know
if(from.balance >= amount){
from.balance = from.balance - amount;
to.balance = to.balance + amount;
System.out.println("Funds successfully transfered.");
} else {
System.out.println("Insufficient funds");
}
}
}
package banking;
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args) {
System.out.println("Hello and welcome to the banking system. Please enter a name to create an account, no spaces: ");
Scanner scan = new Scanner(System.in);
Account a1 = new Account();
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
int count = 0;
while(count == 0) {
System.out.println("What would you like to do next?" + "\n" +
"Change account name: press 1" + "\n" +
"See account name: press 2" + "\n" +
"Check balance: press 3" + "\n" +
"Add money to balance: press 4" + "\n" +
"Withdraw money from balance: press 5" + "\n" +
"Exit program: press 7: " + "\n" +
"To transfer funds between accounts: press 6");
int toDo = scan.nextInt();
if(toDo == 1) {
System.out.println("Enter new account name: ");
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 2) {
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 3) {
System.out.println("Current balance: $" + a1.getBalance());
}
else if(toDo == 4) {
System.out.println("Desired amount to add: $");
a1.addFunds(scan.nextDouble());
System.out.println("Money successfully added to balance.");
}
else if(toDo == 5) {
System.out.println("Desired amount to withdraw: $");
a1.withdraw(scan.nextDouble());
System.out.println("Money successfully withdrawn from balance.");
}
else if(toDo == 6) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
//this is what i need help with, I don't know what to do with these three things, and since the first two arent accounts, i cant run the transfer method on them
}
else if(toDo == 7) {
System.out.println("Thank you for using our banking system. Until next time.");
count = 1;
}
}
}
}
I can't do anything with the user input because I need the desired accounts in order to run the transfer method with them.
You need to keep track of all the accounts in a List or maybe a Map. Then you using the user input you search and retrieve the desired accounts. Also I don't think you need the transfer method in the Account object you can just use withdraw and addFunds from the main, or maybe have it like a static method. Also I think you will need a few additional operations, like create new account and maybe a login that will just change the active account. Currently you only have 1 account which is a1 so it makes no sense to transfer anything.
I think I understand what you are saying, I already checked your code but I think there's a bit of redundant code in there, like your "Account from". If you are the owner of an account and you are transferring to another do you need to specify your account number? You understand?
Secondly, it's best your multiple ifs and else-ifs to switch case statements.
class bankAccount {
String name;
private double balance;
private final long acctNum = ThreadLocalRandom.current().nextLong(100000000, 999999999);
public bankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
System.out.println("HELLO " + name + ", Your account number is: " + acctNum);
}
public void setName(String name) {
this.name = name;
}
public void addFunds(int amount) {
this.balance += amount;
}
public void withdrawFunds(int amount) {
this.balance -= amount;
}
public double getBalance() {
return balance;
}
public long getAcctNum() {
return acctNum;
}
public void transfer(bankAccount name, double amount) {
if(this.balance >= amount) {
name.balance += amount;
this.balance -= amount;
System.out.println("Transaction Successful");
}
else {
System.err.println("Insufficient Funds!");
}
}
}
class BankSimulator {
static bankAccount John = new bankAccount("John", 50000);
static bankAccount James = new bankAccount("James", 3000);
public static void main(String[] args) {
John.transfer(James, 300);
System.out.println("John's new balance is "+ John.getBalance());
System.out.println("James' new balance is "+ James.getBalance());
}
}
since you'll be making use of another account, you should create two instances of the Account class, this would clarify the ambiguity between which accounts to transfer to.
Essentially all I did was create the Account class, created an instance named John(John's Account) and create an instance named James (James' Account), so now, There you go with two account classes, with different fields but similar methods (getBalance(), transfer(), getAcctNum(), addFunds(), withdrawFunds()).
I Hope this is what you need, Happy Coding!
I suggest you create dummy data (existing) Account first:
List<Account> accountList = new ArrayList<>();
Account acct1 = new Account("tester1", 100.0);
Account acct2 = new Account("tester2", 100.0);
accountList.add(acct1);
accountList.add(acct2);
Add constructor for Account for easier adding of Accounts:
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
Store new account account in list:
accountList.add(a1);
For your procedure for "(toDo == 6)" which is for transfer:
Check first if accountList has at least 2 accounts because it won't make sense if there's only 1 account.
else if (toDo == 6) {
if (accountList.size() > 2) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
for (Account account : accountList) {
if (account.getName().equals(fromAccount)) {
account.withdraw(moneyToTransfer);
}
if (account.getName().equals(toAccount)) {
account.addFunds(moneyToTransfer);
}
}
} else
System.out.println("Cannot transfer.");
}
Also consider if the account actually exists, so add additional checking. Hope this helps!
I know this conversation was from awhile ago, however, must mention to definitely Not use a static method as anthony suggested in this type of situation because a static method can only access static variables and methods.
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 ;)