I am using a toString method to display data in an arraylist. I need it to print out number of accounts, balance of each account, and a total balance. I'm almost sure that my loop is being used wrong/wrong location. But I can't figure out how to fix it. Also when I use the accounts.clear() the total balance clears, but number of accounts stays the same should I have another loop? Any help that you all can give will be greatly appreciated, thanks.
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;
}
}
And here is my Person class
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();
}
}
The output should look something like this:
Num Accounts: 3
bal = 2234.34
bal = 4523.29
bal = 45.62
Total Balance = 6803.25