Using a method from one class into another class - java

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

Seems that you forgot to pass the fee parameter to adjust() method. Following code works perfectly fine
public void monthlyFee(double fee) { //monthly fee for bank accounts
for(int i = 0; i < bank.length; i++) {
if(bank[i] != null) {
System.out.println(bank[i].adjust(fee));
} //I have tried BankAccount.adjust() and couldn't work, bank[i].adjust() nothing seems to work
}
}
Create bank1
One account
Joe Mac owns the account 1234 with the balance of $1000.00
Two accounts
Joe Mac owns the account 1234 with the balance of $1000.00
Sally Ride owns the account 2345 with the balance of $2000.00
Three accounts
Joe Mac owns the account 1234 with the balance of $1000.00
Sally Ride owns the account 2345 with the balance of $2000.00
Pat Armstrong owns the account 3456 with the balance of $3000.00
Monthly Fee
997.05
1997.05
2997.05
Joe Mac owns the account 1234 with the balance of $997.05
Sally Ride owns the account 2345 with the balance of $1997.05
Pat Armstrong owns the account 3456 with the balance of $2997.05
Errors:
No errors found!!!

Simple: when you check your test code, you find that it passes a double value when that adjust() method is invoked!
Your other code (the one that leads to the error) seems to not pass any double when invoking that method!

Related

Java: ArrayList item not returning when searched for

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

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

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

How to transfer funds from one account to another in java, using user input for each desired account, and amount to transfer

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.

Java Bank Account Logic

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");
}
}

Combining two accounts [closed]

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.

Categories