简体   繁体   English

扫描仪比打印快?

[英]Scanner faster than print?

I have encountered a strange problem.我遇到了一个奇怪的问题。

So far, my code looks like this:到目前为止,我的代码如下所示:

String value = "";
Scanner scanner = new Scanner(System.in);

System.out.print("String 1");
System.out.println("String 2");
value = scanner.nextLine();

When I look at this I'd expect the program to print the following当我看到这个时,我希望程序打印以下内容

String 1String 2

and after that it should wait for me to input something.之后它应该等我输入一些东西。

But when i run the Code, it says this:但是当我运行代码时,它会说:

Exception in thread "main" String 1String2
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)

and then it tells me the line in which the error occured.然后它告诉我发生错误的行。

So to me it looks like the scanner tries to scan something, before the Strings get printed.所以对我来说,扫描仪似乎在打印字符串之前尝试扫描某些东西。 Why is this happening?为什么会这样?

The ordering issue happens because the strings are written to stdout, while the exception (due to your environment not allowing keyboard input) is written to stderr.发生排序问题是因为字符串被写入标准输出,而异常(由于您的环境不允许键盘输入)被写入标准错误。

While the strings are written first, the two pieces of data are ending up in two different queues (presumably pipe buffers) with no inherent ordering between them.虽然首先写入字符串,但两条数据最终进入两个不同的队列(可能是 pipe 缓冲区),它们之间没有固有的顺序。 The order you're shown then depends on how/when the environment reads the output from the two queues and merges them for display.然后显示的顺序取决于环境如何/何时从两个队列中读取 output 并将它们合并以进行显示。

If you'd like predictable ordering, you have to write both to the same underlying stream, as contents within a single stream is ordered.如果您想要可预测的排序,则必须将两者写入相同的底层 stream,因为单个 stream 中的内容是有序的。

You can do that from the Java side by writing the strings to stderr (eg System.err.println instead), or from the environment side by ensuring that stdout and stderr point to the same stream (eg shell java SomeProgram 2>&1 ) You can do that from the Java side by writing the strings to stderr (eg System.err.println instead), or from the environment side by ensuring that stdout and stderr point to the same stream (eg shell java SomeProgram 2>&1 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM