Java 运行简单程序时发生编译错误
我有一个编程作业,要求我编写一个名为Account的类,包括各种方法等,以及一个测试程序。我已经完成了这一切,除了一些错误,但我不知道它是什么。有人能帮我吗?程序无法编译Java 运行简单程序时发生编译错误,java,Java,我有一个编程作业,要求我编写一个名为Account的类,包括各种方法等,以及一个测试程序。我已经完成了这一切,除了一些错误,但我不知道它是什么。有人能帮我吗?程序无法编译 import java.util.Date; public class Account { private int id = 0; private double balance = 0; private double annualInterestRate = 0; private stati
import java.util.Date;
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private static Date dateCreated = new Date();
Account(){
id = 0;
balance = 0;
annualInterestRate = 0;
dateCreated = new java.util.Date();
}
Account(int newId, double newBalance, double newAnnualInterestRate){
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
public int getId(int id){
return id;
}
public int setId(int newId){
return newId;
}
public double getBalance(double balance){
return balance;
}
public double setBalance(double newBalance){
return newBalance;
}
public double getAnnualInterestRate(double newAnnualInterestRate){
return newAnnualInterestRate;
}
public double setAnnualInterestRate(double newAnnualInterestRate){
return newAnnualInterestRate;
}
public Date getDateCreated(Date getDateCreated){
return dateCreated;
}
public double getMonthlyInterestRate(){
return balance * annualInterestRate / 12;
}
public double getMonthlyInterest(double getMonthlyInterestRate){
return balance * getMonthlyInterestRate;
}
public double withdraw(double amount){
return balance - (balance - amount);
}
public double deposit(double amount){
return (balance + amount) - balance;
}
}
public class testAccount {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.setId(1122);
account.setBalance(20000);
account.setAnnualInterestRate(4.5);
account.withdraw(2500);
account.deposit(3000);
account.dateCreated();
System.out.println("Balance is: " + account.balance);
}
}
只要看一眼代码,有一点是错误的,那就是这一行:
account.dateCreated();
account.balance();
您没有一个名为that的方法。您有一个名为getDateCreated的,这就是您的意思吗
另一个问题是这一行:
account.dateCreated();
account.balance();
同样,您可能是指account.getBalance
这两种方法在代码中都有必需的参数,但它们可能不应该像JonK在评论中提到的那样。getter通常不接受任何参数
无论哪种方式,都可以发布您收到的错误。我可以在这里看到三个问题: 您不能使用account.balance,因为balance在account类中具有私人访问权限。这意味着您只能在Account类中使用此变量。 您可以将balance变量公开,也可以使用getBalance方法 您声明的所有get方法getId和getBalance将始终返回传递给它们的参数,而不是实际的变量。这是因为参数与实例变量同名,因此将其隐藏。 典型的getter没有任何参数,因此可以去掉它们。如果确实需要从具有同名参数的方法中引用实例变量,请使用this关键字,即this.balance引用实例变量,balance引用参数
dateCreated方法似乎也不存在。在打印语句的末尾,使用account.getBalance.toString而不是account.balance 还可以去掉公共类testAccount中的关键字public 对于方法getDateCreatedDate getDateCreated,可以删除参数,而只使用getDateCreated 使用account.dateCreated时,请改用account.getDateCreated
编译,它应该工作 如果未编译,则必须有编译错误?您收到的确切错误是什么?不允许account.balance私人访问,使用getter。我想这与Account类没有名为dateCreated的方法这一事实有关……当您不知道为什么某些内容无法编译时,请始终指定编译错误,并在理想情况下将程序简化为无法编译的最小示例。您已经在这里提供了近100行代码-我怀疑如果您一点一点地删除一些内容,直到得到一个最小的示例,您就能够自己解决这个问题。值得一提的是,OP定义的getDateCreated方法也带有日期参数,尽管我不知道为什么