Question 7-3

[15 pts] Define a class PigPen for tracking the number of pigs in in a pen. It should support the following methods.

PigPen(int pigs)
(Constructor method) Constructs an object representing a pig pen containing pigs pigs.

boolean isEmpty()
Returns true if there are no pigs in the pen.

void pigEnters()
Adds one to the number of pigs in the pen.

void pigExits()
Subtracts one from the number of pigs in the pen.

For example, if you defined this class properly, I should be able to write the following class to test it.
public class PigPenTest {
    public static void run() {
        PigPen pen = new PigPen(2);
        pen.pigExits();
        IO.println(pen.isEmpty()); // prints ``false''
        pen.pigExits();
        IO.println(pen.isEmpty()); // prints ``true''
        pen.pigEnters();
        IO.println(pen.isEmpty()); // prints ``false''
    }
}

Solution

public class PigPen {
    private int count;

    public PigPen(int pigs) {
        count = pigs;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public void pigEnters() {
        count++;
    }

    public void pigExits() {
        count--;
    }
}

Back to 8:00 Quiz 7