How to print an Array List on multiple lines?

后端 未结 3 862
慢半拍i
慢半拍i 2021-01-22 05:16

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?<

相关标签:
3条回答
  • 2021-01-22 05:28
     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);
      }
    }
    
    0 讨论(0)
  • 2021-01-22 05:33

    Just iterate over the list and print each item seperately:

      public void printMeals() {
        for(String meal : meals) {
            System.out.println(meal);
        }
      }
    
    0 讨论(0)
  • 2021-01-22 05:47

    In Java 8

    public void printMeals() {
        this.meals.stream().forEach(System.out::println);
    }
    
    0 讨论(0)
提交回复
热议问题