如何在多行上打印数组列表? [英] How to print an Array List on multiple lines?

查看:79
本文介绍了如何在多行上打印数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上MOOC Java课程,但我坚持练习76.每当我提交答案时,它都会告诉我将每顿饭打印在单独的一行中.我将如何去做?

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?

主类

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();
    }
}

菜单类

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);
      }

}

输出

[Fish fingers with sour cream sauce, Vegetable casserole with salad cheese, Chicken and nacho salad]

推荐答案

只需遍历列表并分别打印每个项目:

Just iterate over the list and print each item seperately:

  public void printMeals() {
    for(String meal : meals) {
        System.out.println(meal);
    }
  }

这篇关于如何在多行上打印数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆