简体   繁体   中英

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. The order you're shown then depends on how/when the environment reads the output from the two queues and merges them for display.

If you'd like predictable ordering, you have to write both to the same underlying stream, as contents within a single stream is ordered.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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