无法对非静态字段进行静态引用

无法对非静态字段进行静态引用

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

我的主要问题是我不断收到一条错误消息: 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;
    }   }


茅侃侃
浏览 1217回答 3
3回答

慕的地6264312

main是一种静态方法。它不能引用balance,这是一个属性(非静态变量)。 balance仅在通过对象引用(例如myAccount.balance或yourAccount.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;}

喵喔喔

线条account.withdraw(balance, 2500);account.deposit(balance, 3000);你可能想要撤销和存入非静态,并让它修改余额public void withdraw(double withdrawAmount) {     balance = balance - withdrawAmount;}public void deposit(double depositAmount) {     balance = balance + depositAmount;}并从通话中删除balance参数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java