It seems like I can't call the withdraw method.. What did I do wrong?
public class BankAccount {
double balance;
BankAccount(double openingBalance){
balance=openingBalance;
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance += amount;
}
public void withdraw (double amount){
if (balance > amount){
balance -= amount;
}else if (amount > balance){
System.out.print("Error");
}else if (amount == balance){
balance = 0;
}
}
}
My driver class
public class Driver {
static BankAccount acc1;
public static void main (String[] args){
BankAccount acc1 = new BankAccount (1500);
acc1.deposit(1500);
acc1.withdraw(1000);
System.out.println("Withdrawl Amount: $" +acc1.withdraw(I GET AN ERROR) +"Deposit: $" +acc1.balance);
The problem is that you are invoking acc1.withdraw(...) and trying to append whatever it returns to a String. Since the withdraw method returns void, that is not valid syntax. It isn't clear what you really want but if you want to append the return value of withdraw to a String for some reason then withdraw needs to return something. Maybe you want something like this...
public class BankAccount {
double balance;
BankAccount(double openingBalance){
balance=openingBalance;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance += amount;
}
public double withdraw (double amount){
if (balance > amount){
balance -= amount;
}else if (amount > balance){
System.out.print("Error");
}else if (amount == balance){
balance = 0;
}
// you can return the amount, or the balance, or whatever you want here...
return amount;
}
}
One way to invoke the method...
public class Driver {
public static void main (String[] args){
BankAccount acc1 = new BankAccount (1500);
System.out.println("After Withdrawing Amount: $" +acc1.withdraw(50) +" The New Balance: $" +acc1.balance);
}
}
Related
I apologize ahead of time if this code isn't formatted correctly, trying to paste instead of retyping each line. If it isn't right, can someone tell me an easy way to paste multiple lines of code at once?
My main question is that I keep getting an error message stating: Cannot make a static reference to the non-static field balance.
I have tried making the methods static, with no result, and making the main method non-static by removing "static" from the header, but then I get the message: java.lang.NoSuchMethodError: main Exception in thread "main"
Does anyone have any ideas? Any help is appreciated.
public class Account {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
System.out.println("The account was created " + account.getDateCreated());
}
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public void setId(int i) {
id = i;
}
public int getID() {
return id;
}
public void setBalance(double b){
balance = b;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double interest) {
annualInterestRate = interest;
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
public static double withdraw(double balance, double withdrawAmount) {
double newBalance = balance - withdrawAmount;
return newBalance;
}
public static double deposit(double balance, double depositAmount) {
double newBalance = balance + depositAmount;
return newBalance;
}
}
main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))
I made some changes to your code so that it compiles.
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);
and:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
public void deposit(double depositAmount) {
balance += depositAmount;
}
the lines
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
you might want to make withdraw and deposit non-static and let it modify the balance
public void withdraw(double withdrawAmount) {
balance = balance - withdrawAmount;
}
public void deposit(double depositAmount) {
balance = balance + depositAmount;
}
and remove the balance parameter from the call
You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.
The static calls to withdraw and deposit are your problem.
account.withdraw(balance, 2500);
This line can't work , since "balance" is an instance variable of Account. The code doesn't make much sense anyway, wouldn't withdraw/deposit be encapsulated inside the Account object itself? so the withdraw should be more like
public void withdraw(double withdrawAmount)
{
balance -= withdrawAmount;
}
Of course depending on your problem you could do additional validation here to prevent negative balance etc.
Just write:
private static double balance = 0;
and you could also write those like that:
private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;
To access instance variables it is a must to create an object, these are not available in the memory, before instantiation.
Therefore, you cannot make static reference to non-static fields(variables) in Java. If you still, try to do so a compile time error is generated saying “non-static variable math cannot be referenced from a static context”.
you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below.
sb = starting balance and eB = ending balance.
Account account = new Account(1122, 20000, 4.5);
double sB = Account.withdraw(account.getBalance(), 2500);
double eB = Account.deposit(sB, 3000);
System.out.println("Balance is " + eB);
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
account.setDateCreated(new Date());
System.out.println("The account was created " + account.getDateCreated());
accumulating totals in CheckingAccount class is not outputting correct total
I am not sure what I am doing wrong. I know I am not passing the value correctly, but can not figure it out and have worked many hours trying to resolve it, but nothing works.
abstract class BankAccount {
double balance = 0.0;
double totalBalance;
double deposit;
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance(double balance) {
return this.balance;
}
public void setTotalBalance(double totalBalance) {
this.totalBalance = totalBalance;
}
public double getTotalBalance(double totalBalance) {
return deposit + balance;
}
public void setDeposit(double deposit) {
this.deposit = deposit;
}
public double getDeposit(double deposit) {
return this.deposit;
}
public abstract void debitAccount();
public abstract void creditAccount();
}
import java.util.ArrayList;
public class BankAccountTestDrive {
public static void main(String[] args) {
ArrayList<BankAccount> bankAccountArray = new ArrayList<BankAccount>();
BankAccount checkingAccount = new CheckingAccount();
BankAccount autoLoan = new AutoLoan();
autoLoan.creditAccount();
checkingAccount.creditAccount();
checkingAccount.setBalance(62.00);
checkingAccount.setDeposit(6.00);
checkingAccount.setDeposit(10.00);
checkingAccount.setDeposit(4.00);
bankAccountArray.add(checkingAccount);
autoLoan.setBalance(30.00);
autoLoan.setBalance(2000.00);
bankAccountArray.add(autoLoan);
for (BankAccount bankaccount : bankAccountArray) {
bankaccount.creditAccount();
}
System.out.println("Checkiing Balance " + checkingAccount.getBalance(0));
System.out.println("Auto loan Balance " + autoLoan.getBalance(0) + "\n");
System.out.println("Total accounts: " + bankAccountArray.size());
}
}
class CheckingAccount extends BankAccount {
public void creditAccount() {
balance = deposit += balance;
}
#Override
public void debitAccount() {
balance -= balance;
}
}
each deposit needs to be added to the balance to accumulate a total for checkingAccount and the same for AutoLoan.
expected output:
Checkiing Balance 70.0
Auto loan Balance 1970.0
Total accounts: 2
I have created an account class but the after the first calculation the it continues and doubles the second line. Have I missed anything in the code.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=Math.pow(balance*(1+rate),n/12);
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(500, 0.1);//0.10);
Account acc2 = new Account(400, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
acc1.deposit(500);
acc1.withdraw(300);
acc1.computeInterest(12);
acc1.computeInterest(24);
System.out.println(acc1.computeInterest(12));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(200);
acc2.deposit(800);
acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
I don't know whether I have missed out something or that I have wrote the code wrong.
acc1.computeInterest(12);
acc1.computeInterest(24);
It looks to me that what you want is that calling these functions only return the computed interest but it shouldn't change your balance variable.
Just return the computed value without saving it in #balance variable.
This is my interpretation of your question, you were a little bit vague.
You have used the method computeinterest(int n) twice for the object acc1. the first time when you have used acc1.computeInterest(12) you get a value for it, but as you have used acc1.computeInterest(24) after that you are getting the answer incorrect.
I create a very basic bank account program for homework and I keep getting a logic error. Instead of the program giving the total balance after the depositing, withdrawing, and adding interest it just outputs the amount deposited - withdrawn.I appreciate the help, thanks!
public class BankAccount
{
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public void deposit(double amtDep)
{
balance = balance + amtDep;
}
public void withdraw(double amtWd)
{
balance = balance - amtWd;
}
public void addInterest()
{
balance = balance + balance * interest;
}
public double checkBal()
{
return balance;
}
private double balance;
private double interest;
}
Test Class
public class BankTester
{
public static void main(String[] args)
{
BankAccount account1 = new BankAccount(500, .01);
account1.deposit(100);
account1.withdraw(50);
account1.addInterest();
System.out.println(account1.checkBal());
//Outputs 50 instead of 555.5
}
}
I believe the problem is in your constructor:
public BankAccount(double initBalance, double initInterest)
{
balance = 0; // try balance = initBalance
interest = 0; // try interest = initInterest
}
Change your constructor as
public BankAccount(double initBalance, double initInterest)
{
balance = initBalance;
interest = initInterest;
}
You are not assigning the value you are passing to the constructor to the instance variables
In the constructor you are by default assigning the values as 0 for balance and interest, instead assign the method parameters. Replace the below code
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public BankAccount(double initBalance, double initInterest)
{
this.balance = initBalance;
this.interest = initInterest;
}
Ok, so I hope you can all help, I have been tasked whilst tying to learn the language with the age-old test of simple savings account and checking account using inheritence.
My problem is, I want to make the checking account incapable of going over its overdraft limit and the savings account incapable of going below 0 but cant work out how? my code so far is as follows:
SUPERCLASS (BankAccount):
public class BankAccount
{
protected String CustomerName;
protected String AccountNumber;
protected float Balance;
//Constructor Methods
public BankAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn)
{
CustomerName = CustomerNameIn;
AccountNumber = AccountNumberIn;
Balance = BalanceIn;
}
// Get name
public String getCustomerName()
{
return (CustomerName);
}
// Get account number
public String getAccountNumber()
{
return (AccountNumber);
}
public float getBalance()
{
return (Balance);
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance - WithdrawAmountIn;
}
public void Deposit(float DepositAmountIn)
{
if(DepositAmountIn < 0)
System.out.println("Sorry, you can not deposit a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance + DepositAmountIn;
}
} // End Class BankDetails
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
}
Thank you very very much for any advice and help!
Add getOverdraftAmount() to your base class:
public int getOverdraftAmount() {
return 0;
}
Then override that method in account subclasses that allow overdrafts. Then revise your logic for withdrawal to take into account that the overdraft limit might not be zero.
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance - WithdrawAmountIn < -getOverdraftAmount()) {
System.out.println("Sorry, this withdrawal would exceed the overdraft limit");
else
Balance = Balance - WithdrawAmountIn;
}
To do this you will need to override the withdraw function in both the subclasses in order to change the functionality of each individually.
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (WithdrawAmountIn>Balance)
System.out.println("Sorry, you don't have this much in your account.");
else
Balance = Balance - WithdrawAmountIn;
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance-WithdrawAmountIn<getOverdraftAmount()
System.out.println("Sorry, you cannot withdraw this much");
else
Balance = Balance - WithdrawAmountIn;
}
}