我只是有我敢肯定是一個非常容易和快速的問題在這裏......所以我們可以說我有一個帳戶類,如下所示:與陣列迭代循環
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