Debugging do-while loop appear more than one statements

Asad Mehmood :

I write a code for o-while loop where I take an input from user and check if it is equal to 'c' or 'C' the exit from the loop. If input other than c or C entered the internal statement of do block is appearing 3 times and if i just enter press without pressing any character then do block's inner statement appears 2 times why?? Can anyone explain

int ch = 0;
        do {
            System.out.println("Press C or c to continue.");
            ch = System.in.read();
        }
        while(ch !='C' && ch !='c');
Sweeper :

(Judging from the output you described, you are probably on a Windows machine, right?)

read returns the next character in the input stream. When you enter C or c, and then press enter, you have actually entered three characters:

  • c
  • \r
  • \n

The last two characters together is the Windows way of representing a new line. Since there are three characters to read, read gets called three times before you are prompted to enter anything again, so println gets called three times as well.

If you just press enter, then you have only entered two characters:

  • \r
  • \n

so two lines are printed.

To fix this, you can use a java.util.Scanner. Scanner has a nice method called nextLine, which returns everything the user enters until it reaches a new line character.

Scanner sc = new Scanner(System.in);
String line = "";
do {
    System.out.println("Press C or c to continue.");
    line = sc.nextLine();
}
while(!ch.equals("C") && !ch.equals("c"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131249&siteId=1