I have an assignment to create a class Purse and print the coins in the purse, reverse the sequence of the coins, transfer the contents of one purse to another, and compare to see if two purses have the same contents. I have the following code but the transfer is not working correctly because it is leaving out the last coin and the same contents is not showing correctly which ones have the same contents. I cannot use any methods from the collections or arrays class.
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Purse
{
public Purse()
{
coins = new ArrayList<String>();
}
public void addCoin(String coinName)
{
coins.add(coinName);
}
public String toString()
{
return "Purse" + coins;
}
public int countCoins()
{
return coins.size();
}
public void reverse()
{
for(int i = 0; i < coins.size() / 2; i++)
{
String coin1 = coins.get(i);
String coin2 = coins.get(coins.size()-1-i);
coins.set(i,coin2);
coins.set(coins.size()-1-i,coin1);
}
}
public void transfer (Purse other)
{
for(int i = 0; i < other.coins.size();i++)
{
coins.add(other.coins.get(i));
other.coins.clear();
}
}
public boolean sameContents(Object other)
{
boolean isSame = false;
for (int i = 0; i < coins.size(); i++)
{
if (!(coins.get(i).equals(coins.get(i))))
isSame = false;
else
isSame = true;
}
return isSame;
}
private ArrayList<String> coins;
}
public class PurseTester
{
public static void main(String[] args)
{
Purse p = new Purse();
p.addCoin("Quarter");
p.addCoin("Dime");
p.addCoin("Nickel");
p.addCoin("Dime");
System.out.println("Original purse: " + p.toString());
System.out.println("Expected: Purse[Quarter,Dime,Nickel,Dime]");
p.reverse();
System.out.println("Reversed purse: " + p.toString());
System.out.println("Expected: Purse[Dime,Nickel,Dime,Quarter]");;
Purse a = new Purse();
a.addCoin("Quarter");
a.addCoin("Dime");
a.addCoin("Nickel");
a.addCoin("Dime");
Purse b = new Purse();
b.addCoin("Dime");
b.addCoin("Nickel");
a.transfer(b);
System.out.println(a.toString());
System.out.println("Expected: Purse[Quarter, Dime, Nickel, Dime, Dime, Nickel]");
System.out.println(b.toString());
System.out.println("Expected: Purse[]");
Purse u = new Purse();
u.addCoin("Quarter");
u.addCoin("Dime");
Purse v = new Purse();
v.addCoin("Quarter");
v.addCoin("Dime");
System.out.println(u.sameContents(v));
System.out.println("Expected: true");
Purse w = new Purse();
w.addCoin("Nickel");
w.addCoin("Dime");
w.addCoin("Nickel");
Purse x = new Purse();
x.addCoin("Nickel");
x.addCoin("Dime");
x.addCoin("Quarter");
System.out.println(w.sameContents(x));
System.out.println("Expected: false");
Purse y = new Purse();
y.addCoin("Nickel");
y.addCoin("Dime");
y.addCoin("Nickel");
Purse z = new Purse();
z.addCoin("Nickel");
z.addCoin("Dime");
System.out.println(x.sameContents(z));
System.out.println("Expected: false");
}
}