Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1.) Implement a class Purse. A purse contains a collection of coins. For simplic

ID: 3652353 • Letter: 1

Question


1.) Implement a class Purse. A purse contains a collection of coins. For simplicity, we will only store the coin names in an ArrayList<String>.

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]

---------------------------------------------------
2.) Write a method reverse that reverses the sequence of coins in a purse. Use the toString method of the preceding assignment to test your code. For example, if reverse is called with a purse

Purse[Quarter, Dime, Nickel, Dime]

----then the purse is changed to

Purse[Dime, Nickel, Dime, Quarter]

--------------------------------------------------
3.) Add a method
public void transfer(Purse other)
that transfers the contents of one purse to another.

For example, if a is

Purse[Quarter, Dime, Nickel, Dime]

and b is

Purse[Dime, Nickel]
then after the call a.transfer(b), a is

Purse[Quarter, Dime, Nickel, Dime, Dime, Nickel]

and b is empty.

-----------------------------------------

4.) Write a method for the Purse class

public boolean sameContents(Purse other)
that checks whether the other purse has the same coins in the same order.
---------------------------------------------------

5.) Write a method for the Purse class
public boolean sameCoins(Purse other)
that checks whether the other purse has the same coins, perhaps in a different order.

For example, the purses
Purse[Quarter, Dime, Nickel, Dime]
and
Purse[Nickel, Dime, Dime, Quarter]
should be considered equal. You will probably need one or more helper methods.

Explanation / Answer

Since ArrayList is parameterized, you'll need to specify the type it contains when you construct it: public Purse() { coins = new ArrayList(); } Then you can add strings to it at will: public void addCoin(String coinName) { coins.add(coinName); } You can also very simply iterate over the contents of the list to print each item: public String toString() { if (coins.isEmpty()) return "Purse[]"; StringBuilder sb = new StringBuilder("Purse["); for (int i=0, size=coins.size(); i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote