我正在编写一个跟踪不同交易的程序
随着时间的推移完成。我有一个主班,还有另一个班CheckingAccount.java
。
我有这样格式化的主类。
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);
}
}
这是我的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;
}
}
因此,我无法上班的行是主类函数中的
CheckingAccount.setBalance()
和CheckingAccount.setServiceCharge()
。我想做的是从在主类(setBalance
和setServiceCharge
)上创建的函数调用在类中创建的方法(processCheck
和processDeposit
)。但是我无法使其运行,我继续运行这些错误消息。
非静态方法setBalance(double,int,double,boolean)不能从静态上下文中引用
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
最佳答案
您正在通过类名调用setBalance
,这是错误的。...setBalance()
方法是非静态的,因此它是针对该类的特定实例而不是针对某个类的。
**CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);**
您需要创建
CheckingAccount
的实例才能调用该方法。其次,在
constructor
类的CheckingAccount
中,您没有为totalService
传递任何参数,但是您正在使用未知变量设置一个。您将在那里收到编译器错误。
您需要使用固定值初始化
totalServiceCharge
,或者可以将其作为来自main的参数传递。并按如下所示更改构造函数。public CheckingAccount(double initialBalance, ** double totalServiceCharge)
{
balance = initialBalance;
this.totalServiceCharge = totalServiceCharge;
}
然后从main调用,如下所示:-
CheckingAccount ca = new CheckingAccount(bal, totalServiceCharge);