该计划应在12个月和24个月后计算2个账户的利息.这很好用.我的问题是利率的getter/setter不起作用,所以当利率在另一个类私有变量中保存为0.1时,我无法从主类中打印出来.
public class testAccountIntrest{
//main method
public static void main(String[] args) {
//creating objects
Account account1 = new Account(500);
Account account2 = new Account(100);
//printing data
System.out.println("");
System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
System.out.println("");
System.out.println("");
System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
System.out.println("");
System.out.println("The intrest rate is " + getIntrest());
}//end main method
}//end main class
class Account {
//instance variables
private double balance;
private double intrestRate = 0.1;
//constructor
public Account(double initialBalance) {
balance = initialBalance;
}
//instance methods
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public void setIntrest(double rate) {
intrestRate = rate;
}
public double getIntrest() {
return intrestRate;
}
public int computeIntrest(int n) {
double intrest = balance*Math.pow((1+intrestRate),(n/12));
return (int)intrest;
}
}
Run Code Online (Sandbox Code Playgroud)
由于编译器无疑是在告诉你,你的testAccountIntrest类不具有一个名为方法getInterest().所以这一点在该类的上下文中无法做任何事情:
getInterest()
Run Code Online (Sandbox Code Playgroud)
但是,你的Account班级确实有这种方法.并且您在该范围内有两个Account 对象:
Account account1 = new Account(500);
Account account2 = new Account(100);
Run Code Online (Sandbox Code Playgroud)
所以你可以在那些对象上调用该方法:
account1.getInterest()
Run Code Online (Sandbox Code Playgroud)
要么:
account2.getInterest()
Run Code Online (Sandbox Code Playgroud)
基本上,您必须告诉代码您正在调用方法的对象.它无法自行解决.