Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用BufferedReader或Scanner处理多个输入_Java_String - Fatal编程技术网

在Java中使用BufferedReader或Scanner处理多个输入

在Java中使用BufferedReader或Scanner处理多个输入,java,string,Java,String,当我试图用这个程序读取所有行时,它会给我少一行作为输出 示例程序: String line = null; Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { line = scanner.nextLine(); System.out.println(line); } scanner.close(); 当我将标准输入作为: ab cd ef gh 输出为: ab cd ef “scan

当我试图用这个程序读取所有行时,它会给我少一行作为输出

示例程序:

String line = null;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) 
{
  line = scanner.nextLine();
  System.out.println(line);
}
scanner.close();
当我将标准输入作为:

ab
cd
ef
gh
输出为:

ab
cd
ef

“scanner.hasNextLine()”。最后一行没有下一行,因此它在打印ef之前存在循环。

可能重复解释如何将标准输入作为。为什么您认为它在循环时退出
?@SotiriosDelimanolis我认为代码实际上可以工作。。。我自己测试过。@jstnchng如果在输入的末尾添加一个额外的回车符,它将“起作用”(如中所示,它将打印最后一行)。OP似乎没有这样做。他是通过一个文件来输入的。当循环开启时。“Line=scanner.nextLine()”将把索引推到第“gh”行。然后在下一个循环中检查下一行。行“gh”没有“nextLine”,因此它将在打印行“gh”上的任何内容之前退出循环。我的回答是对的,你不应该投反对票:/当他们特别在
中显示
系统时,为什么你认为它是一个文件?