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

Time:12-14

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:

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

CodePudding user response:

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).

  •  Tags:  
  • java
  • Related