我有一个while循环,它检测sc.hasNext()是否为true并接受输入的输入列表,将其逐个添加到列表textEditor中。
while (sc.hasNext()) {
String line = sc.nextLine();
if (!(line.isEmpty())){
textEditor.addString(line);
}
}
sc.close();
textEditor.printAll();
}
}
但是,当我输入字符串列表时,例如
oneword
two words
Hello World
hello World
循环不会停止,并且不会调用printAll()方法。如何突破while循环?
在break
语句中没有while
,所以你进入无限循环。
我用简单的System.out.println
改编了你的例子。看一下新的while
条件,当收到一个空字符串时,它将退出while语句:
Scanner sc = new Scanner(System.in);
String line;
while (!(line = sc.nextLine()).isEmpty()) {
System.out.println("Received line : " + line);
//textEditor.addString(line);
}
sc.close();
System.out.println("The end");
您可以使用break语句中断循环:
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (!(line.isEmpty())){
textEditor.addString(line);
} else {
break;
}
}
textEditor.printAll();
(顺便说一句,不要关闭stdout,stderr或stdin,即Java:System.out,System.err和System.in)