How to transfer funds from one bank account to another in Java? - java

Assignment:
Change the Account class so that funds can be moved form one account to another. Think of this as withdrawing money from one account and depositing it into another. Change the main method of Banking class to show this new service.
I am working on a bank account class that can deposit and withdraw money from bank account balances. I am working on the class part of the the assignment where you declare all the methods for the driver. My assignment wants me to make a method that will withdraw money from one account and deposit that money into another account. I already know how to withdraw and deposit, I just don't know how to transfer money from one account to another account. Here is my code for the transfer method so far:
import java.text.NumberFormat;
public class Account
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
public double transfer (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
//What should I put here to deposit the amount into another account?
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns the account number.
//-----------------------------------------------------------------
public long getAccountNumber ()
{
return acctNumber;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}

There is no purpose to your transfer method. Tranfer should be a method in your main class which instantiates the accounts. Example of a transfer would be.
public static void main(String[] args)
{
// This creates two different accounts :)
Account a = new Account("userA", 123, 200);
Account b = new Account("userB", 234, 500);
// Tranfer
a.withdraw(100, 5);
System.out.println(a.getBalance());
b.deposit(100);
System.out.println(b.getBalance());
}
and turning this into a method would be
public static void transfer (Account from, Account to, double amount, double fee)
{
from.withdraw(amount, fee);
to.deposit(amount);
}
EDIT
If i understood your second question correctly, you want to create a default account? If i misunderstood, can you provide more details? (link to the assignment or something)
You need to write 6 new methods for it, you don't already have them,
getOwner
setOwner
getAcctNumber
setAcctNumber
getBalance
setBalance
Account CLass
import java.text.NumberFormat;
public class Account
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
public Account()
{
// This would be the default constructor and default account
name ="N/A";
acctNumber = 0;
balance = 0.0;
}
//-----------------------------------------------------------------
// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns the account number.
//-----------------------------------------------------------------
public long getAccountNumber ()
{
return acctNumber;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}
Drvier Class
public class test
{
public static void main(String[] args)
{
// Created here
Account defaultAccount = new Account();
Account a = new Account("userA", 123, 200);
Account b = new Account("userB", 234, 500);
System.out.println(defaultAccount.getBalance());
// Tranfer
a.withdraw(100, 5);
System.out.println(a.getBalance());
b.deposit(100);
System.out.println(b.getBalance());
}
public static void transfer (Account from, Account to, double amount, double fee)
{
from.withdraw(amount, fee);
to.deposit(amount);
}
}

Create a method transfer(String ID, double amount) that utilises the deposit(String Id, double amt) and withdrawal(double amount) methods to transfer the funds.

Related

Howto make the withdraw stop when the balance below 25$

Here my code.
Main SavingsDemo.java
public class SavingsDemo
{
public static void main(String[] args)
{
// Create a SavingsAccount object with a $100 balance,
// 3% interest rate, and a monthly service charge
// of $2.50.
SavingsAccount savings =
new SavingsAccount(100.0, 0.03, 2.50);
// Display what we've got.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some deposits.
savings.deposit(25.00);
savings.deposit(10.00);
savings.deposit(35.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some withdrawals.
savings.withdraw(100.00);
savings.withdraw(50.00);
savings.withdraw(10.00);
savings.withdraw(1.00);
savings.withdraw(1.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Do the monthly processing.
savings.monthlyProcess();
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
}
}
Superclass BankAccount.java
public class BankAccount
{
private double balance; //The balance in the account
private int numDeposits; //Number of deposits this month
private int numWithdrawals; //Number of withdrawals
private double interestRate; //Annual interest rate
private double monthlyServiceCharge; //Monthly service charge
/**
The constructor
Accept arguments for the balance and annual interest rate.
#param bal To hold the number of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the number of monthly service charge.
*/
public BankAccount(double bal, double intRate, double mon)
{
balance = bal;
interestRate = intRate;
monthlyServiceCharge = mon;
}
/**
This method to hold the amount of deposit.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
balance = balance + amount;
numDeposits++;
}
/**
This method to hold the amount of withdrawal.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
balance = balance - amount;
numWithdrawals++;
}
/**
This method to update the balance by calculating the monthly interest
earned by the account.
*/
private void calcInterest()
{
double monIntRate;
double monInt;
monIntRate = (interestRate / 12.0);
monInt = balance * monIntRate;
balance = balance + monInt;
}
/**
This method to calculate the monthly service charge.
*/
public void monthlyProcess()
{
balance = balance - monthlyServiceCharge;
calcInterest();
numWithdrawals = 0;
numDeposits = 0;
monthlyServiceCharge = 0;
}
/**
This method to hold the number of monthly service charge.
#param amount The number of monthly service charge.
*/
public void setMonthlyServiceCharges(double amount)
{
monthlyServiceCharge += amount;
}
/**
This method to return the amount of balance.
#return The amount of balance.
*/
public double getBalance()
{
return balance;
}
/**
This method to return the number of deposits.
#return The number of deposits.
*/
public int getNumDeposits()
{
return numDeposits;
}
/**
This method to return the number of withdrawals.
#return The number of withdrawals.
*/
public int getNumWithdrawals()
{
return numWithdrawals;
}
/**
This method to return the number of annual interest rate.
#return The number of annual interest rate.
*/
public double getInterestRate()
{
return interestRate;
}
/**
This method to return the amount of monthly service charge.
#return The amount of monthly service charge.
*/
public double getMonthlyServiceCharge()
{
return monthlyServiceCharge;
}
}
Subclass SavingsAccount.java
public class SavingsAccount extends BankAccount
{
private boolean status;
/**
The constructor
To accept the argument of balance, interest rate and monthly charge.
#param bal To hold the amount of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the amount of monthly service charge.
*/
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
/**
This method to determine whether the account is inactive before withdrawals
is made.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
/**
This method to determine whether the account is inactive before a
deposit is made.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
if (status = true)
{
super.deposit(amount);
}
}
/**
This method to check the number of withdrawals.
*/
public void monthlyProcess()
{
if (getNumWithdrawals() > 4)
{
setMonthlyServiceCharges(getNumWithdrawals() - 4);
}
super.monthlyProcess();
if (getBalance() < 25)
{
status = false;
}
}
}
As the question above. I want to make only two withdraw because in the main program when I do 2 withdraw, the balance will become 20$ and it become inactive. But somehow my code did withdraw 5 times. So can someone give me an idea how to solve this problem. Thanks!
Change
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}
and
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}

How to allow the user to access methods of a class

I am working a programming project from Java textbook that says:
The L&L bank can handle up to 30 customers who have savings accounts. Design and implement a program that manages the accounts. Keep track of key information and let each customer make deposits and withdrawals. Produce error messages for invalid transactions. Hint: You may want to base your accounts on the Account class from Chapter 4. Also provide a method to add 3 percent interest to all accounts whenever the method is invoked.
I am not certain on what the question is specifically asking but my guess is to allow and enable the user to add accounts, deposit, withdraw, add interest, get balance, and print the accounts being managed into an array. I am not entirely sure that I have to make an array but the whole chapter is on arrays.
My problem is that I am not sure how to enable the user to make an account
(EX: Account acct1 = new Account ("Ted Murphy", 72354, 102.56);),
to deposit money (EX: acct1.deposit (25.85);),
withdraw money (EX: acct3.withdraw (800.00, 0.0);),
add interest (EX: acct1.addInterest();),
or to print an array for all the accounts.
Here is the Account class found in the Java textbook with all the methods:
//********************************************************************
// Account.java Author: Lewis/Loftus/Cocking
//
// Represents a bank account with basic services such as deposit
// and withdraw.
//********************************************************************
import java.text.NumberFormat;
public class Accounts
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035; // interest rate of 3.5%
private int acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Accounts (String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
public double addInterestAll ()// I made this method myself but I am not sure if it is correct
{
balance += (balance * 0.03);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns the account number.
//-----------------------------------------------------------------
public int getAccountNumber ()
{
return acctNumber;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}
Here is the main method that is under construction and I am not sure if I am on the right track:
import java.util.Scanner;
public class SixSix
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Input (0) to add account, (1) to deposit,");
System.out.println("(2) to withdraw, (3) to add interest, (4) to add interest to all");
System.out.println("(5) to get balance, (6) to get account number, (7) to print");
int input = scan.nextInt();
while (input == 0){
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
System.out.println("Please enter your account number");
int accNum = scan.nextInt();
System.out.println("Please Enter account balance");
double accBalance = scan.nextDouble();
//System.out.format
}
while (input == 1)
{
System.out.println("To deposit money to an account");
}
while (input == 2)
{
System.out.println("To withdraw money from an account");
}
while (input == 3)
{
System.out.println("To add Interest");
}
while (input == 4)
{
System.out.println("To add Interest to all");
}
while (input == 5)
{
System.out.println("To get balance");
}
while (input == 6)
{
System.out.println("To get account number");
}
while (input == 7)
{
System.out.println("Printing account");
}
}
}
It seems to me like you're on the right track. I'm inferring from the way the question (in the book) is phrased and the code that you've posted that the accounts don't already exist, in which case you need to allow the user of the system to create them. Then when altering an account, the user would first have to supply the account number so that you can identify the proper Accounts object.
I'm guessing that since the chapter was on arrays, it probably hasn't covered Maps yet (which would otherwise be a convenient way of associating account numbers to Accounts objects). If you use arrays, then having the account numbers range from 0 to 29 seems like a good idea.
Here's an example of how you could implement an AccountsManager class that helps you add and retrieve accounts from an array of accounts.
public class AccountsManager {
private Accounts[] accounts;
private final int capacity;
private int current;
public AccountsManager(int capacity) {
this.capacity = capacity;
accounts = new Accounts[capacity];
current = 0;
}
// returns the account number of the new account
// or -1 if no account could be made
public int addAccount(String name) {
if (current >= capacity) {
return -1;
}
accounts[current] = new Accounts(name, current, 0);
return current++;
}
public Accounts getAccount(int number) {
if (number >= current || number < 0) {
return null;
}
return accounts[number];
}
}
In the above, the capacity attribute is simply the size of the array, which is the maximum number of Accounts objects that can be created (this should be 30, according to the exercise). The current attribute (feel free to rename to something more informative!) keeps track of where in the array the next Accounts object should be created. This grows by one each time an account is added.
In your code, you could now do something like this:
AccountsManager manager = new AccountsManager(30);
// ...
if (input == 0) {
// Create new account
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
int accountNumber = manager.addAccount(name);
if (accountNumber == -1)
System.out.println("The bank can't handle any more accounts.");
else
System.out.println("Your account number is "+accountNumber);
} else if (input == 1) {
// Deposit money to account
System.out.println("What is your account number?");
int accountNumber = scan.nextInt();
// Check if account exists
if (manager.getAccount(accountNumber) == null) {
System.out.println("That account doesn't exist!");
} else {
System.out.println("How much do you want to deposit?");
double amount = scan.nextDouble();
manager.getAccount(accountNumber).deposit(amount);
}
}
Perhaps it might be preferable to create new methods in the AccountsManager class to make deposits etc, but this shows at least what the general structure could be like.

Bank Account TransferTo Method

Ok I am having problems creating a transfer to method to transfer "money" from one account to the next. After the transfer the amounts of each account would be printed out. I created the code but when I run it the amount transferred is set to the bank account amount. It should just deduct from one account and add to the next account. What am I doing wrong?
This is my class with contructors and methods:
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account(int account, double balance) {
this.balance = balance;
}
public Account() {
balance = 0.0;
}
// Instance methods
public void setBalance() {
balance = Math.random() * 1000;
balance = Math.round((balance * 100.0)+.5) / 100.0;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public double getBalance() {
balance = Math.round((balance * 100.0)+.5) / 100.0;
return balance;
}
public void close() {
balance = 0.0;
}
public void transferTo(Account bank, double x) {
if (x <= balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
} else if (x > balance) {
System.out.println("\nTransfer failed, not enough balance!");
}
}
}
This is my class with the main method
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
System.out.println("Accounts 1 balance is: $" + bank[0].getBalance());
System.out.println("Accounts 2 balance is: $" + bank[1].getBalance());
System.out.println("Accounts 3 balance is: $" + bank[2].getBalance());
System.out.println("Accounts 4 balance is: $" + bank[3].getBalance());
double x = Math.random()*100;
bank[0].transferTo(bank[1], x);
System.out.println("Remaining balance of Account 1: $" + bank[0].getBalance());
System.out.println("Remaining balance of Account 2: $" + bank[1].getBalance());
double y = (Math.random()*300);
bank[2].transferTo(bank[3], y);
System.out.println("Remaining balance of Account 3: $" + bank[2].getBalance());
System.out.println("Remaining balance of Account 4: $" + bank[3].getBalance());
}
}
One issue you did have, is that you were accidentally printing the BALANCE rather than the amount actually transferred, in your transferTo() method. I fixed this. On another note, if you're going to be printing these numbers out, look into printf() to make them appear as actual dollar amounts. I did it to one of the lines to show you an example.
PS - Try NOT using Math.random() for stuff when you're trying to debug.
public void transferTo(Account bank, double x) {
if (x <= this.balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + x);
} else { //does not need to be else if, because if not <=, it MUST be >.
System.out.println("\nTransfer failed, not enough balance!");
}
}
I can verify that the method works perfectly fine, after these edits, on my machine. This is what I used to test:
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
double x = 100.00;
System.out.printf("Transferring $%.2f from Acc 1 to Acc 2.\n", x); //printf example
System.out.println("Acc 1 previous balance: " + bank[0].getBalance());
System.out.println("Acc 2 previous balance: " + bank[1].getBalance());
bank[0].transferTo(bank[1], x);
System.out.println("Acc 1 new balance: " + bank[0].getBalance());
System.out.println("Acc 2 new balance: " + bank[1].getBalance());
}
}
And lastly, my output:
Transferring $100.00 from Acc 1 to Acc 2.
Acc 1 previous balance: 106.76
Acc 2 previous balance: 266.18
Transfer succesful. Transfered: $100.0
Acc 1 new balance: 6.77
Acc 2 new balance: 366.19
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
This prints the other account's new balance, because that's what you told it to do.
If you want to print the amount transferred:
System.out.println("\nTransfer succesful. Tansfered: $" + x);
// Bank account class
class BankAccount {
constructor(fname, lname, account_number) {
const minBalance = 10000;
this.name = `${fname} ${lname}`;
this.balance = minBalance;
this.account_number = account_number;
}
details() {
console.log(
`Cleint name: ${this.name} \n Balance: ${this.balance} \n Account number: ${this.account_number}`
);
}
isPositive(amount) {
return amount > 0 ? true : false;
}
isVlaidAmount(amount) {
return isNaN(amount) || !this.isPositive(amount) ? false : true;
}
deposit(amount) {
if (this.isVlaidAmount(amount)) {
this.balance += amount;
} else {
console.log("Sorry, this transcation cannot be completed!");
}
}
withdraw(amount) {
if (this.isVlaidAmount(amount)) {
this.balance -= amount;
} else {
console.log("Sorry, you have insufficient funds.");
}
}
transfer(amount, reciever) {
if (this.isVlaidAmount(amount)) {
this.withdraw(amount);
reciever.deposit(amount);
}
}
}
// create objects
let acc1 = new BankAccount("George", "Omara", 422);
let acc2 = new BankAccount("Haward", "Walowets", 662);

Account class not working properly

public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());

Bank Account Program Issue

For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.

Categories

Resources