I am writing a program that keeps track of different transactions
done over time. I have a main class, and also another class named
CheckingAccount.java.
I have a main class formatted this way.
public class Main
{
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
--line of code---
--line of code---
--line of code---
}
public static int getTransCode()
{
--line of code---
}
public static double getTransAmt()
{
--line of code---
}
public static void processCheck(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
}
This is my CheckingAccount.java
public class CheckingAccount
{
private double balance;
private double totalServiceCharge;
public CheckingAccount(double initialBalance)
{
balance = initialBalance;
totalServiceCharge = totalServiceCharge;
}
public double getBalance()
{
return balance;
}
public void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge = totalServiceCharge+currentServiceCharge;
}
}
So the lines I can’t get to work are CheckingAccount.setBalance() and CheckingAccount.setServiceCharge() inside the functions on my main class. What I’m trying to do is to call the the methods I created (setBalance, and setServiceCharge) in my class, from functions that I created on my main class (processCheck, and processDeposit).
But I cannot get it to run, I keep running with these error messages.
non-static method setBalance(double,int,double,boolean) cannot be referenced from a static context
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
You are calling your
setBalancethrough classname which is wrong….setBalance()method is non-static, so it is defined to specific instance of the class, not for a class..You need to create an instance of
CheckingAccountto call the method..Secondly, in your
constructorofCheckingAccountclass, you haven’t passed any argument fortotalService, but you are setting one with an unknown variable..You will get a compiler error there..
Either you need to initialize your
totalServiceChargewith a fixed value or, you can pass it as an argument from main.. And change your constructor as below..Then from main, call it like this: –