Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A very simple java do...while loop [duplicate]

Tags:

java

do-while

I am learning JAVA and typed the following DO...WHILE example. The program will quit if I type 'q'. It runs but why I get three rows of "Please a key followed by ENTER:"?

class DWDemo {
    public static void main (String args[])
      throws java.io.IOException {
          char ch;
          do {
              System.out.println("Please a key followed by ENTER:");
              ch = (char) System.in.read();
          } while (ch != 'q');
      }
}

enter image description here

like image 492
JACKY Li Avatar asked Nov 11 '15 13:11

JACKY Li


3 Answers

Because when you type a and hit Enter, then the in.read() method returns three characters - 'a', the character for carriage return \r and the character for line break ('\n'). (Note that the combination \r\n is considered as line-break under Windows).

Your program will have significantly different behavior if you run it under Linux or OSX, because line-breaking character(s) is specific to the OS you're running the program on. Under Linux, it will be \n, under OS X-9 it will be \r, for example.

As a work-around, you can read the whole line (by using a Scanner) and trim it, which will omit the line-breaking character (disregarding the OS type):

public static void main (String args[]) throws java.io.IOException {
      String line;
      Scanner sc = new Scanner(System.in);
      do {
          System.out.println("Please a key followed by ENTER:");
          line = sc.readLine().trim();
      } while (!"q".equals(line));
  }
like image 127
Konstantin Yovkov Avatar answered Nov 01 '22 21:11

Konstantin Yovkov


I assume what gets read as input is containing your ENTER keypress. Since you are on Windows, this includes the CRFL line ending.

Thus, each time you entered your char, you actually input 3 chars. For your first input:

  1. a
  2. CR
  3. LF

Try reading a full line via a BufferedReader and run a whitespace trim on that, or just evaluate its first char.

like image 36
kasoban Avatar answered Nov 01 '22 21:11

kasoban


When typing input on a command line on a Windows system, all lines are ended in a line feed consisting of the characters \r\n. So when you type a that first time, you are actually typing a\r\n.

When the code System.in.read() is run, it reads just the first character that has been entered into the buffer, in this case a. Then the loop runs, prints out your prompt and tries to read the next character on the buffer. In this case the \r\n is still on the buffer so it reads in \r. Loops again and it reads in \n. Finally it prints the prompt a third time since the buffer is empty, it waits for your input.

In order to avoid this I would suggest using a different method to read in from the command line instead of System.In. Perhaps the Scanner class would be more appropriate.

like image 3
Evan Frisch Avatar answered Nov 01 '22 23:11

Evan Frisch