So i am a beginner in
Java and learning from a book. I understand how a do-while loop works. It runs at least one time, and the condition is tested at the bottom. If it's false, the loop ends. Now i have a question about a little part in the following code:
The book explains this: Here is why this loop is needed: As explained earlier, System.in is line buffered—you have to
press ENTER before characters are sent. Pressing ENTER causes a carriage return and a line feed
character to be generated. These characters are left pending in the input buffer. This loop
discards those characters by continuing to read input until neither is present.
I googled for an hour, looked in video's but could not find an in depth answer. I tested the program without the loop, and then it prints "Sorry you're wrong' two times. I understand that when i choose a letter and press enter, a carriage return and newline character is also created. I don't really understand how this loop prevents that these unwanted characters are used. It's this loop:
So in example, i press the letter S. I give an enter. So if i am understanding correctly, the System.in.read receives: S, \n, \r. Three characters. So, the S is not a \n or \r, so the while loop won't run again right? Then it goes to the else part. But how is the pending in the input stream, the \n and \r removed? I don't get the order of the program, can somebody explain this with more detail?