运行以下代码的结果是:
Final account balance is: -97.0
但答案应该是150.0,对吗?我哪里出错?
class Account
{
double initBalance;
Account(double initBalance)
{
initBalance=this.initBalance;
}
double getBalance()
{
return initBalance;
}
void deposit(double amt)
{
initBalance=initBalance + amt;
}
void withdraw(double amt)
{
initBalance=initBalance - amt;
}
}
class TestAccount
{
public static void main(String args[])
{
Account acct=new Account(100);
acct.deposit(50);
System.out.println("Final account balance is: " +acct.getBalance());
}
}
答案 0 :(得分:8)
Account(double initBalance) {
initBalance=this.initBalance;
}
必须是
Account(double initBalance) {
this.initBalance=initBalance;
}
答案 1 :(得分:3)
这是不对的:
Account(double initBalance)
{
initBalance=this.initBalance;
}
应该是:
this.initBalance = initBalance;
答案 2 :(得分:2)
问题在于你的构造函数,试试这个
Account(double initBalance)
{
this.initBalance = initBalance;
}
这正是为什么方法参数应该具有与实例变量不同的名称的原因,并且还应该优先使用final来避免这样的错误。如果您的构造函数参数是最终的,编译器本身会警告您。良好实践
Account(final double pInitBalance)
{
initBalance = pInitBalance;
}
答案 3 :(得分:1)
更改构造函数的代码。这种变体是对的:
Account(double initBalance) {
this.initBalance = initBalance;
}
答案 4 :(得分:0)
class Account
{
public double initBalance;
public Account(double initBalance)
{
this.initBalance = initBalance;
}
double getBalance()
{
return initBalance;
}
void deposit(double amt)
{
initBalance=initBalance + amt;
}
void withdraw(double amt)
{
initBalance=initBalance - amt;
}
}
public class TestAccount
{
public static void main(String args[])
{
Account acct=new Account(100);
//System.out.println("account balance after deposit 100 is: " +acct.getBalance());
acct.deposit(50);
//System.out.println("account balance after deposit 100 + 50 is: " +acct.getBalance());
System.out.println("Final account balance is: " +acct.getBalance());
}
}
这是正确的代码。检查一下。