因此,作为免责声明,我对编程非常陌生,并且可能缺少明显的东西。现在,我尝试创建两个名为withdraw()和deposit()的方法,这些方法将允许我更改字段currentBalance的值,但是,每次尝试使用这两个方法更改currentBalance的值时,我都会检查我的方法getBalance()获得字段的值,并且始终保持不变。
class TradingService{
public class Trader {
//This field stores the trader's name
private String traderName;
//This field stores the trader's current balance
private double currentBalance;
//A constructor to create a Trader
public Trader(String traderName) {
this.traderName = traderName;
}
//This method gets returns the trader's name
public String getName() {
return traderName;
}
//This method set's the trader's name
public void setName(String traderName) {
this.traderName = traderName;
}
//This method decreases the trader's balance
public void withdraw(double withdrawAmount) {
this.currentBalance = (currentBalance - withdrawAmount);
}
//This method increases the trader's balance
public void deposit(double depositAmount) {
this.currentBalance = (currentBalance + depositAmount);
}
//This method returns the trader's current balance
public double getBalance() {
return currentBalance;
}
}
}
我正在使用DrJava,并且正在“交互”面板中测试我的代码。这是我测试的结果。
> Trader t1
> t1 = new Trader("Bill")
Trader@22e1cbe4
> t1.deposit(10.0)
10.0
> t1.getBalance()
0.0
我已经完成了我可以想象的所有工作来修复代码,但是我没有主意,并且我认为再花3个小时在我的代码中输入随机的内容并不会起到很大的作用。
感谢您抽出宝贵时间阅读我的问题。
最佳答案
类“Trader”看起来很好,可以为我工作。但是您有一个“Trader”类,它是“TradingService”类中的一个公共(public)类,我认为也许该类未在编译,并且您正在执行旧文件,因此可以像内部类一样使用“Trader”类进行尝试。
class Trader {
//This field stores the trader's name
private String traderName;
//This field stores the trader's current balance
private double currentBalance;
//A constructor to create a Trader
public Trader(String traderName) {
this.traderName = traderName;
}
//This method gets returns the trader's name
public String getName() {
return traderName;
}
//This method set's the trader's name
public void setName(String traderName) {
this.traderName = traderName;
}
//This method decreases the trader's balance
public void withdraw(double withdrawAmount) {
this.currentBalance = (currentBalance - withdrawAmount);
}
//This method increases the trader's balance
public void deposit(double depositAmount) {
this.currentBalance = (currentBalance + depositAmount);
}
//This method returns the trader's current balance
public double getBalance() {
return currentBalance;
}
}
public class TradingService{
public static void main(String[] args)
{
Trader t = new Trader("test");
t.deposit(10);
System.out.print(t.getBalance());
}
}