Why does this code only work properly if the method is in a while loop condition? (Java)

I know the System.in.read() method doesn’t have much use, but I’m confused as to why it has to be in the while statement for the following code to work.

I’m trying to take character input from the method and add it to a string. When the enter key is pressed, it stops taking input and prints the exact string of characters that I entered.

Here, when pressing enter, it never prints and continues taking input.

    String str = "";
    char ch = (char) System.in.read();
    
    while (ch != (char)10) {
      str += ch;
    }

    System.out.println(str);

If the method is in both places, it cuts off the first character I type in (so typing "abc" prints "ab"). Using a do while loop fixes this, but I don’t understand why the first loop is being skipped.

    String str = "";
    char ch = (char) System.in.read();
    
    while ((ch = (char) System.in.read()) != (char)10) {
      str += ch;
    }

    System.out.println(str);

When I put the method solely in the while statement, though, the code works as I want it to.

    String str = "";
    char ch;
    
    while ((ch = (char) System.in.read()) != (char)10) {
      str += ch;
    }

    System.out.println(str);
  }
}

Could someone explain this to me? Thanks in advance.

>Solution :

Take a close look at the loop in the last case:

while ((ch = (char) System.in.read()) != (char)10) {
  str += ch;
}

The left side of the condition to evaluate for whether or not to execute the block of code in the while is

(ch = (char) System.in.read())

So each time the condition is evaluated, a character is read from standard input and assigned to the ch variable.

This is then confronted with (char) 10. If ch != (char) 10 the block of code is executed.

A similar way to write this would be

do {
    char ch = (char) System.in.read();
    if (ch == (char) 10) {
        break;
    }
    str += ch;
} while (true);

Leave a Reply