We are going to create three classes that will resemble the following UML:
When interfacePurse is run it will create the following output (input in red):
How many cents is the coin worth? 10 What year is on the coin? 1987 Do you want to stop? (y/n) n How many cents is the coin worth? 100 What year is on the coin? 2000 Do you want to stop? (y/n) y
The total value in the purse is 110 cents. This is in the purse: * a dime with a Bluenose on it, minted in 1987 * a loonie with a loon on it, minted in 2000
Use the comments to fill in the class.
public class coin
{
private int cvalue;
private int cyear;
public coin (int v, int y)
{
//v is the value of the coin, y is the year
//assign them to their instance variables
}
public int year ()
{
//returns the year
}
public int value ()
{
//returns the value of the coin
}
public String name ()
{
//depending on the value of the coin,
//return penny, nickel, dime, quarter, loonie, twoonie
}
public String animal ()
{
//depending on the value of the coin,
//return maple leaf, beaver, Bluenose, caribou, loon, polar bear
}
}
Again, follow the comments and make sure that you compile it!
public class changePurse
{
private coin coins [] = new coin [25];
private int size;
public changePurse ()
{
//set the size to be 0
}
public boolean isFull ()
{
//if the size is less than 25, return false
// because the purse isn't full
}
public void addCoin (int value, int year)
{
if (!isFull ())
{
coins [size] = new coin (value, year);
size++;
}
}
public int totalValue ()
{
//loop through the array of coins and total the values
//return the total value
}
public void printContents ()
{ //use methods from the coin class to print out lines like:
//* a dime with a Bluenose on it, minted in 1987
}
}
public class interfacePurse
{
public static void main (String args [])
{
changePurse mine = new changePurse ();
String quit = "n";
while (quit.equals ("n"))
{
int value = IBIO.inputInt ("How many cents is the coin worth? ");
int year = IBIO.inputInt ("What year is on the coin? ");
mine.addCoin (value, year);
quit = IBIO.inputString ("Do you want to stop? (y/n) ");
}
System.out.println ();
System.out.println ("The total value in the purse is " + mine.totalValue () + " cents.");
System.out.println ("This is in the purse: ");
mine.printContents ();
}
}