简体   繁体   中英

Verifying my knowledge of how an empty Scanner reacts in Java

Is this true?

If you have a scanner attached to System.in, and it's current Buffer is 100% empty, it will always pause whenever it encounters a call to the scanner object.

scan.hasNext();

scan.nextInt();

scan.nextBoolean();

I just want to make sure I am understanding what is going on properly. I am seeing that it pauses when it encounters these in my little test programs but I am wonder if the program always pauses when it encounters these or if it only pauses at these calls when the buffer is empty. Thank you.

If the Scanner needs more characters, then it will attempt to read them from the source. If the source is at its EOF position 1 then the Scanner method will return false or throw an exception (depending on which one you are talking about). Otherwise, it will block.

But the situation is complicated by the fact that those Scanner methods will not necessarily attempt to get characters from the underlying source. In particular, the Scanner itself acts as a buffer for characters that have been read by previous Scanner calls. So for example:

  scanner.hasNext();  // This may attempt to read characters
  scanner.hasNext();  // This won't attempt to read characters

On top of that, the source you are reading from could itself be buffered, either within the JVM or externally.


So, you asked:

If you have a scanner attached to System.in , and it's current Buffer is 100% empty, it will always pause whenever it encounters a call to the scanner object.

What happens depends on:

  • what you mean by "its current Buffer",

  • the nature of the Java 2 and OS-level 3 streams attached to System.in , and

  • the state of the stream.

But, the answer is No. It won't always pause.


1 - Determining this may entail a read syscall ... which will return immediately if the native stream is at the EOF position.

2 - For instance, you could use System.setIn(...) to change what System.in refers to.

3 - For instance, standard input could be coming from a file or another process.

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