In: Computer Science
JAVA PROGRAMMING
Implement a class Purse. A purse contains a collection of coins.
For simplicity, we will only store the coin names in an
ArrayList<String>.
IMP: This is what I have so far. Please correct it.
PURSE CLASS:
import java.util.Collections;
import java.util.ArrayList;
public class Purse {
private ArrayList<String> coins;
public Purse() {
coins = new
ArrayList<String>();
}
public void addCoin(String nameofCoin)
{
}
public String toString()
{
return coins.toString();
}
public String reverse()
{
ArrayList<String> pl = new
ArrayList<String>(coins);
Collections.reverse(pl);
return pl.toString();
}
}
//TEST PURSE CLASS:
public class TestPurse {
public static void main(String[] args) {
Purse pu = new Purse();
pu.addCoin("Dime");
pu.addCoin("Dime");
pu.addCoin("Nickel");
pu.addCoin("Quarter");
System.out.println(pu);
System.out.println("Expected the
Purse: Dime, Dime, Nickel, Quarter");
System.out.println(pu.reverse());
}
}
//Java code (Try this solution)
import java.util.Collections; import java.util.ArrayList; public class Purse { private ArrayList<String> coins; //Constructor public Purse() { coins = new ArrayList<String>(); } public void addCoin(String nameofCoin) { //add coin to the arrayList coins using add() coins.add(nameofCoin); } public String toString() { String result=""; for (String coin:coins ) { result+=coin+", "; } return result; } public String reverse() { ArrayList<String> pl = new ArrayList<String>(coins); Collections.reverse(pl); return pl.toString(); } }
//=========================================
public class TestPurse { public static void main(String[] args) { Purse pu = new Purse(); pu.addCoin("Dime"); pu.addCoin("Dime"); pu.addCoin("Nickel"); pu.addCoin("Quarter"); System.out.println(pu); System.out.println("Expected the Purse: Dime, Dime, Nickel, Quarter"); System.out.println(pu.reverse()); } }
//Output
//If you need any help regarding this solution ........... please leave a comment ........ thanks