K
K
kosyan4ik12021-03-10 13:05:28
Java
kosyan4ik1, 2021-03-10 13:05:28

Why does the for loop make 2-3 passes if the increment is i++?

Came in the book to such an example

class help {
  public static void main (String args[])
    throws java.io.IOException{
      int i;
      System.out.println("Для остановки нажмите клавишу S");
    
      for(i = 0; (char) System.in.read() != 'S'; i++)
      System.out.println("проход #" + i);
  }
  }


But during the test, it turns out 3 passes of the FOR loop if you enter any character, if you just press enter, the loop is executed 2 times, tell me what's the problem? why is it so?

60489a1b640c6091771289.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-03-10
@kosyan4ik1

Because you enter two or three characters. Pressing the enter key sends a carriage return and line feed escape sequence to the console, so you have 1\r\n.

T
twobomb, 2021-03-10
@twobomb

I explain how it works, well, as I assume at least.
First, System.in.read reads 1 byte from the input buffer, and secondly, System.in.read blocks the stream until new input arrives.
So when we enter 1 and press enter, in theory, 3 characters get into the input stream 1 - this is what we entered \ r - carriage return \ n - a new line, and first it reads 1 byte that occupies character 1, enters the loop executes the body , then it reads the carriage return character and executes the body, and then it reads the newline character and executes the body, and then the thread again blocks waiting for input.
BUT! With the character "th" and any Russian letter, not everything is so simple, if the encoding is utf8, then it takes 2 bytes in it, and therefore there should be 4 passes, that is, first it counts the first byte of the character th, then the second byte of the character th, then carriage return followed by a new line. Well, maybe you are using, for example, Windows1251 which supports Russian letters and they occupy just 1 byte there and therefore only 3 passes instead of 4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question