gpt4 book ai didi

java - 意外类型+非静态变量 this 无法从静态上下文错误中引用?

转载 作者:行者123 更新时间:2023-12-01 22:26:16 25 4
gpt4 key购买 nike

我的代码无法编译。如何解决这些错误?

import java.util.*;
public class BankAccount{
private double balance;

public BankAccount(double b) {
balance = b;
}

public double getBalance(){
return balance;
}

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

public boolean withdraw(double d){
if(d > balance){
return false;
} else {
balance -= d;
return true;
}
}
public class SavingsAccount extends BankAccount{
private double interest;
public SavingsAccount(double k, double inRate){
super(k);
interest = inRate;
}

public void gainInterest(){
super.getBalance() = super.getBalance() * interest;
}
}
public static void main(String[] args) {
SavingsAccount test = new SavingsAccount(1000, .05);
test.gainInterest();
System.out.println(test.getBalance());

}

以下错误是

I get the unexpected type error at super.getBalance() = super.getBalance() * interest; and the "non-static variable this cannot be referenced from a static context" at SavingsAccount test = new SavingsAccount(1000, .05);

最佳答案

您无法为方法分配值。

您需要将结果分配给变量或将结果传递给另一个方法,在这种情况下您可以使用deposit,例如...

public void gainInterest(){
deposit(super.getBalance() * interest);
}

关于java - 意外类型+非静态变量 this 无法从静态上下文错误中引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732658/

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