gpt4 book ai didi

java - 不能对非静态字段进行静态引用

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:54 25 4
gpt4 key购买 nike

如果此代码格式不正确,我会提前道歉,尝试粘贴而不是重新输入每一行。如果不对,有人可以告诉我一次粘贴多行代码的简单方法吗?

我的主要问题是我不断收到一条错误消息:无法对非静态字段平衡进行静态引用。

我已经尝试使这些方法成为静态方法,但没有结果,并通过从 header 中删除“static”使 main 方法成为非静态方法,但随后我收到消息:java.lang.NoSuchMethodError: main Exception在线程“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;
}
}

最佳答案

main 是一个静态方法。它不能引用 balance,它是一个属性(非静态变量)。 balance 只有在通过对象引用(例如 myAccount.balanceyourAccount.balance)引用时才有意义。但是当它通过类引用时没有任何意义(例如Account.balance(那是谁的余额?))

我对您的代码进行了一些更改以使其能够编译。

public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);

和:

public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}

public void deposit(double depositAmount) {
balance += depositAmount;
}

关于java - 不能对非静态字段进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com