如果这段代码的格式不正确,我会提前道歉,尝试粘贴而不是重新输入每一行。如果不对,有人可以告诉我一次粘贴多行代码的简单方法吗?
我的主要问题是我不断收到一条错误消息: Cannot make a static reference to the non-static field balance.
我已经尝试使方法静态化,但没有结果,并通过从标头中删除“静态”使主要方法非静态化,但随后我收到消息: java.lang.NoSuchMethodError: main Exception in thread "main"
有人有什么想法吗?任何帮助表示赞赏。
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;
}
}
原文由 jshield 发布,翻译遵循 CC BY-SA 4.0 许可协议
线条
你可能想让取款和存款成为非静态的,让它修改余额
并从调用中删除 balance 参数