2

I'm doing the MOOC java course, and I'm stuck on exercise 76. Whenever I submit the answer it tells me to print each meal to a seperate line. How would I go about doing this?

Main class

public class Main {
    public static void main(String[] args) {
        Menu exactum = new Menu();


        exactum.addMeal("Fish fingers with sour cream sauce");
        exactum.addMeal("Vegetable casserole with salad cheese");
        exactum.addMeal("Chicken and nacho salad");

        exactum.printMeals();


        exactum.clearMenu();
        exactum.printMeals();
    }
}

Menu class

import java.util.ArrayList;

public class Menu {

    private ArrayList<String> meals;

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

     public void addMeal(String meal) {
         if (!meals.contains(meal)) {
         meals.add(meal);      
     }
    }
      public void printMeals() {
          if (!meals.isEmpty())
          System.out.println(this.meals);
      }

      public void clearMenu(){
          meals.removeAll(meals);
      }

}

Output

[Fish fingers with sour cream sauce, Vegetable casserole with salad cheese, Chicken and nacho salad]
1
  • iterate over elements of arraylist public void printMeals() { for(String meal : this.meals) System.out.println(meal); } Commented Feb 24, 2016 at 3:44

3 Answers 3

2

Just iterate over the list and print each item seperately:

  public void printMeals() {
    for(String meal : meals) {
        System.out.println(meal);
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I tried that earlier, but I had it under the addMeal method instead of the print and was wondering why it wouldn't work lol.
0

In Java 8

public void printMeals() {
    this.meals.stream().forEach(System.out::println);
}

Comments

0
 import java.util.ArrayList;

public class Menu {

   private ArrayList<String> meals;

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

 public void addMeal(String meal) {
     if (!meals.contains(meal)) {
     meals.add(meal);      
 }
}
  public void printMeals() {
   if (meals.isEmpty()){
     System.out.println("No Meal Object Found !");
      return;
    }
for(String meal : meals) {
    System.out.println(meal);
    }
   }
  public void clearMenu(){
      meals.removeAll(meals);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.