Object-Oriented Programming with Java, part I – Exercise 76

This exercise adds methods to the class meals to add and remove meals from the array.

My Code

import java.util.ArrayList;

public class Menu {

    private ArrayList<String> meals;

    public Menu() {
        this.meals = new ArrayList<String>();
    }

    // add the methods here
    
    public void addMeal(String meal) {
        if (!this.meals.contains(meal)){
            this.meals.add(meal);
        }
    }
        
        public void printMeals(){
            for (String m : meals) {
                System.out.println(m);
            }
        }
        
        public void clearMenu(){
            meals.removeAll(meals);
        }
    }

Model Code

import java.util.ArrayList;

 

public class Menu {

 

    private ArrayList<String> meals;

 

    public Menu() {

        this.meals = new ArrayList<String>();

    }

 

    // add the methods here

    public void addMeal(String meal) {

        if (!this.meals.contains(meal)) {

            this.meals.add(meal);

        }

    }

 

    public void printMeals() {

        for (String meal: this.meals) {

            System.out.println(meal);

        }

    }

 

    public void clearMenu() {

        this.meals.clear();

    }

}

Comments

The major difference is that the model code uses this.meals.clear whereas I used meals.removeAll(meals) which was a mistake as I forgot the this..

Leave a comment