0

Relatively new to Java and probably a very trivial question but I have been getting super confused. Suppose I have the following program:

 Scanner keyboard = new Scanner(System.in);
 System.out.println(keyboard.hasNext());

When I run this program, it prompts me to enter something, I press enter and then the console output is (obviously) true. But precisely, how does the hasNext() method work? From the Oracle website: returns true if the scanner has another token in its input. In my example, there only one input . How exactly is being read and why exactly do I get true if there's no next input into the program? From what I understand the scanner breaks the input into tokens based on the delimiter (in this case we have the default delimiter), so in my case, say i enter "test", then press enter. The scanner reads up to the white space but then there's no next token to read? Then why is hasNext true?

Hopfully not too silly but I am genuinely confused. Many thanks!

I have tried various runs on the above code and i always get true. (obviously ctrl+D , ctrl+C kill the program)

Kon
  • 11
  • 1
  • "The scanner reads up to the white space" I think you are confused, your current code does not read anything, you do not have `keyboard.nextLine` or `keyboard.next` or any variation that moves the pointer. (I am not the downvoter) – Nexevis Mar 16 '23 at 19:11
  • 1
    https://stackoverflow.com/a/8352102/11434552 might have some information that can help you – Nexevis Mar 16 '23 at 19:14
  • But keyboard.hasNext() asks for input doesn’t it ? At least in the above program , i get true after I enter something. So my question is why do I get true if there’s no next input ? Thanks a lot for your comments – Kon Mar 16 '23 at 19:26
  • The [Javadocs](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNext--) state that "This method may _block_ while waiting for input to scan. The scanner does not advance past any input." It blocks it does not "ask for input" and it does not move past the first character without using another method. – Nexevis Mar 16 '23 at 19:33
  • Here is another answer that pretty much answers your question directly: https://stackoverflow.com/a/29528355/11434552 – Nexevis Mar 16 '23 at 19:36
  • So to summarize I think you are confused on two things. 1 - You need to call a `next` method in order to actually read the data, and 2 - `hasNext` will always be `true` if you are reading from `System.in` and not from a file. – Nexevis Mar 16 '23 at 19:38
  • This is great Nexevis! Appreciate it. – Kon Mar 16 '23 at 19:39

0 Answers0