我正在尝试将用户输入的行读取到数组列表中。
Scanner scan = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<String>();
while (true) {
if (scan.nextLine().equals("")) {
break;
}
for (String s : lines) {
lines.add(scan.nextLine());
}
}
for (int i = 0; i < lines.size(); i++) {
System.out.println(lines.get(i));
}
问题是最后一个 for 循环没有运行。我不太明白为什么break in while循环不仅停止while循环。
最佳答案
我不知道你为什么使用for (String s :lines)
循环。在您的代码中 scan.nextLine()
调用了两次。因此它可能会跳过替代值。此外,lines 没有任何值,因此 for (String s :lines)
条件不允许插入任何值。所以只有它不显示值(value)。
试试这个代码
Scanner scan = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<String>();
String s;
while (true) {
s = scan.nextLine();
if (s.equals("")) {
break;
}
lines.add(s);
}
for (int i = 0; i < lines.size(); i++) {
System.out.println(lines.get(i));
}
关于java - 将输入中的行读取到 arraylist java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25485898/