0

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

user2745043
  • 189
  • 2
  • 7
  • 24

4 Answers4

1

It would simplify your code if you used accounts.size() rather than tracking numberOfAccounts separately and this would solve your problem with accounts.clear().

To match the expected output, use StringBuilder and append to the string to match the ordering: num accounts, balance for loop, total balance, for example:

StringBuilder sb = new StringBuilder();
sb.append(String.format("Number of accounts: %d%n", accounts.size());
// call sb.append in your for loop
sb.append(String.format("Total balance: %d%n", totalBalance);
return sb.toString();

In the above example I used String.format syntax just to show another way to format your output.

Drew MacInnis
  • 8,267
  • 1
  • 22
  • 18
  • Ok thanks that fixed my problem of accounts.clear(), but I'm not familiar with the StringBuilder is there a better way with the toString? I put a local variable of balance before the loop like suggested but still having same problem. I know that only a simple fix is probably needed but I been going over this code for a while and am just missing it. Thanks – user2745043 Sep 05 '13 at 02:15
  • I updated my answer to show a StringBuilder example and the use of String.format. – Drew MacInnis Sep 05 '13 at 11:07
  • updated my code using your suggestion, I'm doing something wrong I get an error like this: java.util.IllegalFormatConversionException. Also should I still have a local balance variable in my loop? Thanks – user2745043 Sep 05 '13 at 13:00
  • A local balance variable would make sense since you wouldn't have to loop over the accounts a second time. Since the balance is a `double` you need to format it with `%f`. See http://stackoverflow.com/questions/4885254/string-format-to-format-double-in-java – Drew MacInnis Sep 05 '13 at 17:02
0

First off, the Person class should not have a balance class field; just get rid of it. It's messing you up because whenever you run toString() this balance field will hold on to the value that was calculated inside of the toString() method call. Then if you call the method again, you will be re-adding the old balance stored in the variable to the current balance information, messing you up.

Next, you need to a new balance local variable before the for loop in your toString() method. Then you can add individual balance data to it inside of the for loop, and print out its content after the for loop has completed its looping. That way it can hold information from each item in the ArrayList, and not keep holding on to and adding to old balance information as your code is currently doing.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Hey you have a simple logical mistake that the for loop in toString method will execute only one line that is balance=a.getBalance(); so if you want add other lines of inside for loop put the codes inbetween this { }

ShihabSoft
  • 23
  • 1
  • 7
  • Sorry, but how do you mean? can you give me an example of how it should look? I tried and I still get the same result of only printing the balance of one account. Thanks. – user2745043 Sep 05 '13 at 02:52
0

Hey here is the code of modified toString method. Instead of using return type String use String[] to store multiple strings.That is int count=0; public String[] toString() { double balance = 0; String s[]=new String[accounts.size()]; for (Account a: accounts) { balance = a.getBalance(); String result; result = ""+balance; s[count]=result; count++; } return s; } Now you can print the string array returned from toString method. public void showDetails(String[] input) { System.out.println("Num Accounts: "+accounts.size()); String result=toString(): for(int i=0;i<result.length;i++) System.out.println("Balance :- "+result[i]); System.out.println("\nTotal Balance: " + getTotalBalance()); } Thats all VOTE UP

ShihabSoft
  • 23
  • 1
  • 7