将对象数组初始化为$ 100

时间:2014-02-23 03:55:55

标签: java arrays object

该程序创建10个帐户,并将余额设置为每个100美元。

我写了一个for循环来初始化余额但是没有用。 AccountArray类中无法识别setBalance()方法 如何为每个帐户分配100美元的余额?

public class AccountArray{

public static AccountArray[] createAccountArray(){

AccountArray[] atm = new AccountArray [10];
for(int i = 0; i < atm.length; i++){
    atm[i] = new AccountArray(setBalance(100));
}
return atm;

  }
}


import java.util.Date;

public class Account{

    public int id = 0;
    public double balance = 0;
    public double annualInterestRate = 0;
    public double withdraw;
    public double deposit;
    java.util.Date date = new java.util.Date();


public Account(){
}

public Account(int id, double balance, double annualInterestRate){
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
}
public Account(int id, double balance, double annualInterestRate, Date date){
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
    this.date = date;
}

public void setID(int id){
    this.id = id; 
}

public int getID(){
    return id;
}


public double getBalance(){
    return balance - withdraw + deposit;
}
public void setAnnualInterestRate(double annualInterestRate){
    this.annualInterestRate = annualInterestRate;
}
public double getAnnualInterestRate(){
    return (annualInterestRate/100);
}

public Date getDateCreated(){
    return date;
}


public double getMonthlyInterestRate(){
    return getBalance() * ((annualInterestRate/100) / 12); 
}
public void withdraw(double withdraw){
    this.withdraw = withdraw;
}

public double deposit(){
    return balance + deposit;
}
public void deposit (double deposit){
    this.deposit = deposit;
}


}

public class TestAccount extends AccountArray{

public static void main(String[] args) {

    Account account1122 = new Account(1122, 20000, 4.5);
    account1122.withdraw(2500);
    account1122.deposit(3000);
    System.out.println("Your account balance is: \t" + "$"+ account1122.getBalance() + 
            "\nYour monthly interest rate is: \t" + "$" + account1122.getMonthlyInterestRate() + 
            "\nYour account was created on: \t" + account1122.getDateCreated());

    //Declare account array */
    AccountArray[] atm;

    //Create Account array */
    atm = createAccountArray();

    System.out.println(atm[i].getBalance);
    }


}

1 个答案:

答案 0 :(得分:2)

您的程序正在尝试创建10个AccountArray个实例, 10 Account个。即使它可以工作,你也可以在静态引用或对象实例的上下文之外调用一个方法 - 它永远不会起作用。

你可能想要做的是:

Account[] atm = new Account[10];
for(int i = 0; i < atm.length; i++){
    atm[i] = new Account();
    atm[i].setBalance(100);
}

...虽然在这种情况下忽略其他构造函数似乎有点......我错了。我将这部分作为练习留给读者。