我正在使用 toString 方法在数组列表中显示数据。我需要它来打印出账户数量、每个账户的余额和总余额。我几乎可以肯定我的循环使用错误/错误的位置。但我不知道如何解决它。另外,当我使用 accounts.clear() 时,总余额会被清除,但账户数量保持不变,我应该有另一个循环吗?大家可以提供的任何帮助将不胜感激,谢谢。
This is my Account Class:
package prob2;
public class Account {
double balance;
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public void addInterest () {
balance += (balance - 1000)*.01;
}
public double getBalance() {
return balance;
}
}
这是我的 Person 类
package prob2;
import java.util.ArrayList;
public class Person {
ArrayList<Account> accounts = new ArrayList<Account>();
//int numberOfAccounts = 0;
double sum;
double balance;
public void addAccount(Account a){
//numberOfAccounts++;
accounts.add(a);
}
public Account getAccount (int i) {
return accounts.get(i);
}
public int getNumAccounts() {
return accounts.size();
}
public double getTotalBalance() {
double sum = 0;
for (Account a: accounts)
sum = sum + a.getBalance();
return sum;
}
public void applyInterest() {
for (Account a: accounts)
a.addInterest();
}
public void removeAccount(int i) {
accounts.remove(i);
//numberOfAccounts--;
}
public void depositFunds(int i, double amount) {
getAccount(i).deposit(amount);
}
public void withdrawFunds(int i, double amount) {
getAccount(i).withdraw(amount);
}
public void clearAccounts() {
accounts.clear();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("Number of accounts: %d%n", accounts.size()));
for (Account a: accounts)
sb.append(String.format("Balance: %d%n", a.getBalance()));
// call sb.append in your for loop
sb.append(String.format("Total balance: %d%n", getTotalBalance()));
return sb.toString();
}
}
输出应如下所示:
Num Accounts: 3
巴尔 = 2234.34
巴尔 = 4523.29
巴尔 = 45.62
总余额 = 6803.25