关于Java:如何使数组列表的get方法更简单?

How do I make this get method for array lists simpler?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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));
    }
}

您好,我正在尝试编写一个代码,它将提示用户输入一个名称,该名称将保存在ArrayList中,然后一旦用户退出并按"x"退出,它将显示列表中的所有名称。但是,如何使system.out.println(guessLists.get());代码比全部输入简单?


放这个代码:

1
2
3
4
5
6
7
8
9
}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));
}

1
2
3
4
for(String s : guestsLists)
{
    System.out.println(s);
}

然后移除

system.out.println("================");


只需使用增强的for循环迭代列表:

1
2
3
4
5
...
for (String name : guestsLists) {
    System.err.println(name);
}
...

当您不需要循环内的索引,但只想遍历集合时,可以使用for循环的形式。在这些情况下,比使用显式索引(或使用显式Iterator)更容易读取(并且代码更少)。

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