[英]Read lines from input into arraylist java
I'm trying to read lines from user's input into arraylist. 我正在尝试将用户输入的行读入arraylist。
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));
}
The problem is that last for loop doesnt run. 问题是last for循环不会运行。 I dont quite understand why break in while loop stops not only while loop. 我不太明白为什么闯入while循环不仅会在while循环中停止。
I dont know why you used for (String s : lines)
loop. 我不知道你为什么使用for (String s : lines)
循环。 In your code scan.nextLine()
called twice . 在代码中scan.nextLine()
被调用了两次。 So it may skip alternative values. 因此,它可能会跳过替代值。 Also lines doesn't have any value, so for (String s : lines)
condition not allow any values to insert. 另外,lines没有任何值,因此for (String s : lines)
条件不允许插入任何值。 So only it doesn't display value. 所以只有它不显示价值。
Try this code 试试这个代码
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));
}
Here use following code 这里使用以下代码
Scanner scan = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<String>();
String s=null;
while (true) {
s=scan.nextLine();
if (s.equals("")) {
break;
}else{
lines.add(s);
}
}
for (int i = 0; i < lines.size(); i++) {
System.out.println(lines.get(i));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.