Friday, February 6, 2009

Second Major Assignment due February 16th







The following two programs comes from Chapter 7 in your textbook. Due Monday February 16th, 2009. Please upload both as one project and make sure to zip it before using FTP.

P7.2
Implement a class Purse. A purse contains a collection of coins. For simplicity, we will only store the coin names in an ArrayList. (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]
Use the following class in your solution:
import java.util.ArrayList;

/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}

/**
Adds a coin to the purse.
@param coinName the coin to add
*/
public void addCoin(String coinName)
{
. . .
}

/**
Returns a string describing the object.
@return a string in the format "Purse[coinName1,coinName2,...]"
*/
public String toString()
{
. . .
}

private ArrayList coins;
}

Use the following class as your tester class:
/**
This class tests the Purse class.
*/
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(p.toString());
System.out.println("Expected: Purse[Quarter,Dime,Nickel,Dime]");
}
}

P7.3


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]
Use the following class in your solution:
import java.util.ArrayList;

/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}

/**
Adds a coin to the purse.
@param coinName the coin to add
*/
public void addCoin(String coinName)
{
. . .
}

/**
Returns a string describing the object.
@return a string in the format "Purse[coinName1,coinName2,...]"
*/
public String toString()
{
. . .
}

/**
Reverses the elements in the purse.
*/
public void reverse()
{
. . .
}

private ArrayList coins;
}

Use the following class as your tester class:
/**
This class tests the Purse class.
*/
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]");
}
}

No comments: