我只是有一个我确定是一个非常简单和快速的问题......所以假设我有一个 Account 类,如下所示:
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.03; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Deposits the specified amount into the account. Returns the
// new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Withdraws the specified amount from the account and applies
// the fee. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "\t" + name + "\t" + fmt.format(balance);
}
}
我创建了此处显示的 Bank 类...
public class Bank
{
Account[] accounts;// = new Account[30];
int count=0;
String name;
public Bank(String name)
{
this.name = name;
accounts = new Account[30];
}
public void addAccount(Account acct)
{
accounts[count] = acct;
count++;
}
public void addInterest()
{
//for (Account acct : accounts)
//acct.addInterest();
for(int i = 0; i < count; i++)
accounts[i].addInterest();
}
}
如果我尝试将 addInterest() 方法与您看到的 for (Account acct: accounts) 循环一起使用,则会收到错误消息。有人可以告诉我为什么会这样吗?我认为这些循环是等价的。提前致谢。