我想允许用户输入字符串直到输入空行,并将字符串存储在 ArrayList 中。我有以下代码,我认为它是正确的,但显然不是。
String str = " ";
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
System.out.println("Please enter words");
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(sc.nextLine());
}
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
最佳答案
当您调用一次 sc.hasNextLine()
和两次 sc.nextLine()
时,您可以多次使用下一行。
相反,调用一次 nextLine()
,然后使用存储结果的变量来检索读取的行:
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(str);
}
关于java - 使用ArrayList进行用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050764/