I am trying to do some practice Java. Right now I am doing exercises from a textbook for fun and I am stuck on one problem. This particular problem requires me to create a class called "Purse" and then create "Coins" which can be added to a given purse. This part I have been able to do. The last part of the exercise is to print the purse by using a toString method. I will show my classes below.
Purse
package exercisePurse;
import java.util.ArrayList;
public class Purse {
private ArrayList<Coin> coins;
public Purse(){
coins = new ArrayList<Coin>();
}
public void addCoin(Coin a){
coins.add(a);
}
public String getCoins(){
String allCoins = coins.toString();
return allCoins;
}
}
Coin
package exercisePurse;
public class Coin
{
String coin;
int value;
public Coin(String coinName, int coinValue){
coin = coinName;
value = coinValue;
}
}
Tester class
package exercisePurse;
import java.util.ArrayList;
public class CoinTester
{
public static void main(String args[]){
Purse purse1 = new Purse();
purse1.addCoin(new Coin("Quarter", 2));
purse1.addCoin(new Coin("Dime", 3));
purse1.addCoin(new Coin("Nickle", 4));
purse1.addCoin(new Coin("Penny", 10));
System.out.println(purse1.getCoins());
}
}
Results of a run
[exercisePurse.Coin@2a139a55, exercisePurse.Coin@15db9742, exercisePurse.Coin@6d06d69c, exercisePurse.Coin@7852e922]
Specifically I know my problem area is here
public String getCoins(){
String allCoins = coins.toString();
return allCoins;
}
What I want is for the purse to display the coin names and values. So something like this:
purse1[Quarters 2, Dimes 3, Nickles 2, Pennies 5]
Any help is appreciated, sorry if this has been asked before because I know there are posts on using toString I just couldn't figure out how to implement a solution in this case.
EDIT:
I need to specifically follow these instructions to consider the exercise complete:
Implement a class Purse. A purse contains a collection of coins. For simplicity, we
will only store the coin names in an ArrayList<String>. (We will discuss a better representation
in Chapter 8.) Supply a method
void addCoin(String coinName)
Add a method toString to the Purse class that prints the coins in the purse in the
format
Purse[Quarter,Dime,Nickel,Dime]