我只是有我敢肯定是一个非常容易和快速的问题在这里......所以我们可以说我有一个帐户类,如下所示:与阵列迭代循环
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);
}
}
我创建了银行类这里显示...
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()方法(ACCT账户:账户)环你看到注释掉。有人可以向我提供有关这是为什么的见解吗?我认为这些循环是相同的。提前致谢。
您收到什么错误? – hvgotcodes 2012-07-23 00:22:43
你曾经叫过addAccount()吗?随着你显示的代码,你已经声明了帐户数组,但你并没有实例化任何Account对象。如果这是错误,你会得到一个NulPointerExxception .... – atk 2012-07-23 00:29:31
作为一般性评论,你应该避免像鼠疫这样的数组。使用['Collections'](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html)(在这种情况下为['Set'](http:// docs。 oracle.com/javase/6/docs/api/java/util/Set.html)似乎是合适的),在其他许多重要功能中,当你为它们'添加()'事物时,它们会自动增长。 – Bohemian 2012-07-23 00:30:36