如何使数组列表的这个 get 方法更简单? [复制]
Posted
技术标签:
【中文标题】如何使数组列表的这个 get 方法更简单? [复制]【英文标题】:How do I make this get method for array lists simpler? [duplicate] 【发布时间】:2016-03-23 12:43:14 【问题描述】: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 中,然后一旦用户按“X”退出并退出,它将显示所有列表中的名称。但是如何制作 System.out.println(guestsLists.get());代码更简单,而不是全部输入?
【问题讨论】:
【参考方案1】:使用增强的for
循环简单地遍历列表:
...
for (String name : guestsLists)
System.err.println(name);
...
当您不需要循环内的索引但只想遍历集合时,可以使用for
循环的这种形式。在这些情况下,它比使用显式索引(或使用显式Iterator
)更容易阅读(并且代码更少)。
另见https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
【讨论】:
【参考方案2】:输入这段代码:
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));
或
for(String s : guestsLists)
System.out.println(s);
并删除
之后的所有系统输出System.out.println("========================");
【讨论】:
以上是关于如何使数组列表的这个 get 方法更简单? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
调用 $.get 方法时如何使 javascript 变量成为全局变量? [复制]
如何获取 Net::OpenSSH->scp_get() 方法复制的文件列表