[英]Trying to read multiple lines of cmd input
我正在尝试编写一个方法:
(可以使用空行来确定输入的结束。)
第一个 syso 执行打印部分,并且第一行也被正确读取,但它永远不会退出 while 循环。 为什么? 一定有结局吗?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
我已经看过以下网站,但它们都没有帮助:
编辑:
同样的错误适用于:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
编辑2:我已经在我的实际项目和一个新的测试项目中尝试过这段代码,但结果不同。 这是该测试的视频。
为什么不使用这个语句?
while (!(line = buffer.readLine()).isEmpty())
在这种情况下发送空行将退出循环。
但是,如果您插入带有空行的大文本(例如,新段落的开头或它们之间的空格)将终止程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.