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

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.

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

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