Question 0-1

Suppose we already have the following Topping class to represent a type of food that might go on top of a pizza.

public class Topping {
    public static final Topping PEPPERONI = new Topping(true);
    public static final Topping SAUSAGE = new Topping(true);
    public static final Topping ONION = new Topping(false);
    public static final Topping GREEN_PEPPER = new Topping(false);
    public static final Topping BLACK_OLIVE = new Topping(false);

    private boolean is_meat;

    private Topping(boolean in_is_meat) {
        is_meat = in_is_meat;
    }

    public boolean isVegetarian() {
        return !is_meat;
    }
}

Write a Pizza class that represents a pizza with up to 7 toppings. Your class should contain the following methods.

Pizza()
Constructs a pizza with no toppings.

void addTopping(Topping what)
Adds the topping what onto the pizza.

boolean isVegetarian()
Returns true if all the toppings on the pizza are vegetarian.

Though it may appear that you need an array to store all the toppings, in fact there's a way to do this without an array.

To test your Pizza class, you can use the following program.

import csbsju.cs160.*;

public class PizzaTest {
    public static void main(String[] args) {
        Pizza p = new Pizza();
        p.addTopping(Topping.ONION);
        IO.println(p.isVegetarian()); // prints ``true''

        p.addTopping(Topping.GREEN_PEPPER);
        IO.println(p.isVegetarian()); // prints ``true''

        p.addTopping(Topping.PEPPERONI);
        IO.println(p.isVegetarian()); // prints ``false''

        p.addTopping(Topping.BLACK_OLIVE);
        IO.println(p.isVegetarian()); // prints ``false''
    }
}

Solution

public class Pizza {
    private boolean is_vegetarian;

    public Pizza() {
        is_vegetarian = true;
    }

    public void addTopping(Topping what) {
        is_vegetarian = is_vegetarian && what.isVegetarian();
    }

    public boolean isVegetarian() {
        return is_vegetarian;
    }
}

Back to Exercise Set 0