C Sc 227 Section: Classes with Instance Variables

Recommended Activities

1.  Implement class PiggyBank

2.  Add method compareTo in String227 (see Code Demos Page)

A PiggyBank objects begins with an initial number of pennies, nickels, and dimes (no quarters to save time). A PiggyBank object can have any number of pennies or nickels added to it any number of times. Each instance must remember its name, and how many pennies and nickels it has. You will be asked to implement the following constructor and methods from scratch given these method headings and unit test:

1.  public PiggyBank(String name) Initializes the object with a name an no money

2.  public String getName() Returns the name of this PiggyBank

3.  public double getTotal() Returns money in the piggy bank (return 0.08 with 8 pennies)

4.  public void addPennies(int p) Adds any number of pennies to the piggy bank (check p >= 1)

5.  public void addNickels(int n) adds any number of nickels to the piggy bank (check n >= 1)

6.  public void smash() Empties the piggy bank of all coins (getTotal would then return 0.0)

public class PiggyBankTest {

@Test public void testGetters() {

PiggyBank aBank = new PiggyBank("College Fund");

assertEquals("College Fund", aBank.getName());

assertEquals(0.0, aBank.getTotal(), 1e-12);

}

@Test public void testAddPennies() {

PiggyBank aBank = new PiggyBank("College Fund");

assertEquals(0.0, aBank.getTotal(), 1e-12);

aBank.addPennies(4);

aBank.addPennies(8);

assertEquals(0.12, aBank.getTotal(), 1e-12);

}

@Test public void testAddNickels() {

PiggyBank aBank = new PiggyBank("College Fund");

assertEquals(0.0, aBank.getTotal(), 1e-12);

aBank.addNickels(2);

aBank.addNickels(7);

assertEquals(0.45, aBank.getTotal(), 1e-12);

}

@Test public void testAddNickels() {

PiggyBank aBank = new PiggyBank("College Fund");

assertEquals(0.0, aBank.getTotal(), 1e-12);

aBank.addNickels(2);

aBank.addNickels(7);

assertEquals(0.45, aBank.getTotal(), 1e-12);

}

@Test public void testSmash() {

PiggyBank aBank = new PiggyBank("To be raided");

// Can smash a PiggyBank with no money

aBank.smash();

assertEquals(0.0 + 0.0, aBank.getTotal(), 1e-12);

aBank.addPennies(4);

aBank.addPennies(8);

aBank.addNickels(2);

aBank.addNickels(7);

assertEquals(0.12 + 0.45, aBank.getTotal(), 1e-12);

aBank.smash();

assertEquals(0.0 + 0.0, aBank.getTotal(), 1e-12);

}

}