5

I just learned that when pressing enter in response to a System.in.read(), the following characters are put into the console buffer, \r\n. So when I input the following 1 into the terminal and press enter, the computer reads that statement as 1\r\n. So shouldn't System.out.println("hello") be excuted twice? Because choice will store the value 1. And then, "hello" will be printed. Then, ignore will hold the value \r. Then, the control will be given while(ignore != '\n') loop. Then, ignore will hold the value \n. And then, "hello" will be printed. And now that ignore = \n, the code will break out of the loop?

class HelpClassDemo {
  public static void main(String args[])
    throws java.io.IOException {
    char choice, ignore;

    for(;;) {
      do {
        System.out.println("Help on:");
        System.out.println("  1. if");
        System.out.println("  2. switch");
        System.out.println("  3. for");
        System.out.println("  4. while");
        System.out.println("  5. do-while");
        System.out.println("  6. break");
        System.out.println("  7. continue\n");
        System.out.print("Choose one (q to quit): ");

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

        do {
          ignore = (char) System.in.read();
          System.out.println("hello"); 
        } while(ignore != '\n');
      } while(choice < '1' | choice > '7' & choice != 'q');

      if(choice == 'q') break;
    }
  }
}
aejhyun
  • 612
  • 1
  • 6
  • 19
  • 1
    where did you learn that? and what makes you think it is true? and when you actually tried, and logged the value of each result of a call to `read`, what did you get? what is your question? – njzk2 Jul 27 '15 at 03:05
  • 1
    Why are you using `System.in.read()` ? You should use [`Scanner`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) – Nir Alfasi Jul 27 '15 at 03:12

1 Answers1

1

I think whether the code will have \r (carriage return), \n (new line) or both \r\n depends upon the platform.

I ran your code on a windows machine and it did print hello twice.

You may want to check the machine you are using and the line separator defined for that environment. Please refer What are the differences between char literals '\n' and '\r' in Java? for further details.

Help on:
  1. if
  2. switch
  3. for
  4. while
  5. do-while
  6. break
  7. continue

Choose one (q to quit): 1
choice1
hello
hello
Community
  • 1
  • 1
Smiles
  • 46
  • 8