package aprilchap3;
/**
*
* @author ericaross
*/
public class SavingsAccount {
double interest;
double balance;
public SavingsAccount() {
balance = 0;
interest = 0.1;
}
public void addInterest() {
balance = interest*balance + balance;
}
public void deposit(double amount) {
balance= balance + amount;
}
public void getBalance(){
return balance;
}
}
``这是SavingsAccountTester类:
package aprilchap3;
/**
*
* @author ericaross
*/
public class SavingAccountTester {
public static void main(String[] args) {
SavingsAccount erica = new SavingsAccount();
erica.deposit(1000);
erica.addInterest();
Double ericaBalance = erica.getBalance() ;
System.out.println(ericaBalance + "this is how much you owe. ");`
}
}
所以问题是我想使用构造函数来设置值而不是存款,但是当我尝试这样做时,错误会出现在储蓄账户声明中。
这里是我想把它放在SavingsAccount erica = new SavingsAccount();
的地方,但是每次都有错误出现,任何人都可以向我展示设置构造函数的最佳方法吗?
答案 0 :(得分:0)
public SavingsAccount() {
balance = 0;
interest = 0.1;
}
你不需要这个。您可以将这些变量的初始值设为。你需要的是
public SavingsAccount(double balance, double interest) {
this.balance = balance;
this.interest = interest;
}
然后您通过new SavingsAcccount(balance, interest)
使用它。
NB我希望并相信这是作业。你永远不应该使用浮点数据类型来赚钱。