Skip to main content

while(ch == '\n' | ch == '\r');

1 reply [Last post]
mariecruie
Offline
Joined: 2011-07-16
Points: 0

Hi All,

I am trying to learn Java and am very new to programming/computing. I have a question. I would be much appriciated if you could answer it with very simple words.

do
{
System.out.println("Press a key following enter");
do
{
ch = (char)System.in.read();
}
while(ch == '\n' | ch == '\r');
}
while(ch!='q');

Qustion 1: I don't understand why the program ignores the carriage return and line feed generated by pressing enter and does not print out 2, 3 or mote times "Press a key following enter". As far as I understand the second loop does "read the character that is entered as long as if there is a line feed or carriage return". When you press enter they are both there and they are read as charachters.

do
{
System.out.println("Press a key following enter");

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

}
while(ch!='q');

Question 2: When I use & insted | in "while(ch == '\n' | ch == '\r'); " the program behaves like in the second code example and prints out "Press a key following enter" as many as characters you entered + carriage return + line feed. Why?

Thank you

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
CodeCook
Offline
Joined: 2011-08-24
Points: 0

Figure out what's going on by printing out everthing is does.

public class Main {
  public static void main(String[] args) throws Exception {
    System.out.println("Working...");

    char ch;
    do {
      System.out.println("Press a key following enter...");
      do {
        System.out.println("reading?");
        ch = (char)System.in.read();
        System.out.println("char read was: " + ((int)ch) );
      }
      while (ch == '\n' | ch == '\r');
      System.out.println("Out of inner loop...");
    }while (ch != 'q');
    System.out.println("Out of outter loop with a 'q'...");

    System.out.println("Done.");
  }
}



Run it with difference scenarios.

<enter> k<enter> q<enter>

1111<enter>2222<enter>hello<enter>q<enter>


And see what happens. You'll figure it out!