如何使这个数组列表的get方法更简单?

时间:2015-12-17 06:27:21

标签: java arraylist methods println

import java.util.*;

public class ChristmasParty
{
    private Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        ChristmasParty cp = new ChristmasParty();
        cp.run();
    }

    public void run()
    {
        menu();
        addName();
    }

    public void menu()
    {
        System.out.println("Welcome to the guests lists program");
        System.out.println("Enter a name or enter X to quit");
    }

    public void addName()
    {
        String nameAdded = "";
        ArrayList<String> guestsLists = new ArrayList<String>();
        do
        {
            System.out.print("Enter a name: ");
            nameAdded = input.nextLine();

            guestsLists.add(nameAdded);
            System.out.println("-----------------------------------------------");
            System.out.println(nameAdded + " has been added to the guests list.");

        }while(!nameAdded.equals("X"));
        System.out.println("Guests lists:");
        System.out.println("========================");
        System.out.println(guestsLists.get(0));
        System.out.println(guestsLists.get(1));
        System.out.println(guestsLists.get(2));
        System.out.println(guestsLists.get(3));
        System.out.println(guestsLists.get(4));
        System.out.println(guestsLists.get(5));
        System.out.println(guestsLists.get(6));
        System.out.println(guestsLists.get(7));
        System.out.println(guestsLists.get(8));
        System.out.println(guestsLists.get(9));
        System.out.println(guestsLists.get(10));
        System.out.println(guestsLists.get(11));
        System.out.println(guestsLists.get(12));
        System.out.println(guestsLists.get(13));
        System.out.println(guestsLists.get(14));
        System.out.println(guestsLists.get(15));
    }
}  

您好,我正在尝试创建一个代码,提示用户输入一个名称,该名称将保存在arraylists中,然后一旦用户退出并退出并退出&#34; X&#34; ,它将显示列表中的所有名称。但是我如何制作System.out.println(guestsLists.get());代码更简单而不是全部输入?

2 个答案:

答案 0 :(得分:4)

输入此代码:

}while(!nameAdded.equals("X"));

System.out.println("Guests lists:");
System.out.println("========================");

for(int i = 0; i < guestsLists.size(); i++)
{
    System.out.println(guestsLists.get(i));
}

OR

for(String s : guestsLists)
{
    System.out.println(s);
}

删除

之后的所有sysouts

的System.out.println( “========================”);

答案 1 :(得分:3)

使用增强的for循环简单地遍历列表:

...
for (String name : guestsLists) {
    System.err.println(name);
}
...

当你不需要循环内的索引时,可以使用for循环的那种形式,但只想迭代集合。在这些情况下,比使用显式索引(或使用显式Iterator)更容易阅读(和更少的代码)。

另见https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html