Java 正在将对象数组初始化为$100

Java 正在将对象数组初始化为$100,java,arrays,object,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 <

该程序创建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;
}


}

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

您可能想做的是:

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

…虽然在这种情况下忽略其他构造函数似乎有点…对我来说是错误的。我把这一部分留给读者作为练习。

您需要在java
setBalance
中详细介绍数组和对象,它是一个方法,但您调用它时,就好像它是一个普通的独立函数一样。仅仅因为您在构造函数的参数列表中调用它,并不能免除您对它的调用方式。另外,您不能真正调用尚未初始化的对象的方法。。。在您尝试调用
setBalance
时,您的对象还不存在,因此没有实际设置平衡的位置我真的很害怕。不要将浮点数用于精确值(货币是精确值)。改用
BigDecimal
。另请参见@MichaelT:虽然你的观点非常正确,但这似乎更像是一项学校作业,而不是处理实际的金钱问题。不要让他们为这件事操心太多。
Account[] atm = new Account[10];
for(int i = 0; i < atm.length; i++){
    atm[i] = new Account();
    atm[i].setBalance(100);
}