简体   繁体   中英

Debugging do-while loop appear more than one statements

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM