Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

System.in.read() returns 3 times when I enter a single character

I’m studying the book Java: A Beginner’s Guide, and where it explains the for loop, it uses a variation where the condition contais an user input:

class ForTest {   
  public static void main(String[] args)   
    throws java.io.IOException { 
 
    int i; 
 
    System.out.println("Press S to stop."); 
 
    for(i = 0; (char) System.in.read() != 'S'; i++) 
      System.out.println("Pass #" + i); 
  }   
}

when I executed this code, the output was different than I expected. After I typed one character and pressed enter, the program printed the "Pass #" three times, instead of one. Why is the loop running more than once?

Here is a sample of the output I’ve got:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a
Pass #0
Pass #1
Pass #2
w
Pass #3
Pass #4
Pass #5
1
Pass #6
Pass #7
Pass #8
2
Pass #9
Pass #10
Pass #11

>Solution :

It is passing more times than you expected because System.in will also read an enter key press as a new line character (\r\n on Windows).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading