Home > other >  Why a loop is running three time in eclipse when the condition is false?
Why a loop is running three time in eclipse when the condition is false?

Time:11-28

public class Menu {

    public static void main(String[] args)
    throws java.io.IOException {
        char choice;
        do {
            System.out.println("Help on:");
            System.out.println(" 1. if");
            System.out.println(" 2. while");
            System.out.println(" 3. do-while");
            System.out.println(" 4. for");
            System.out.println(" 5. switch");
            choice = (char) System.in.read();
        } while(choice < '1' || choice > '5');
    }

}

when i input 0 or greater than 5 it cause the loop to execute three time. like this:

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

How can I fix this problem?

CodePudding user response:

Your while statement is a bit wrong and you are trying to use > and < with char witch doesn't work well using the Scanner class you can then use it to get the next int and then you can use it in the while statement.

Scanner scan = new Scanner(System.in);
int choice;
do {
    System.out.println("Help on:");
    System.out.println(" 1. if");
    System.out.println(" 2. while");
    System.out.println(" 3. do-while");
    System.out.println(" 4. for");
    System.out.println(" 5. switch");
    choice = scan.nextInt();
} while (choice >= 1 && choice <= 5);

CodePudding user response:

The problem is that you press 'enter' after entering '6' which is good, except, this means that there is an 'enter character' (which is a 'character' just as much as '6' is) in between your first input and your second, and the 'char value' is below '1'. On windows, an enter is in fact 2 characters (CR and LF; 13 and 10 respectively, which are far below '1'), hence, 3 loops.

Most likely you want a scanner configured to treat newline symbols as separators:

Scanner s = new Scanner(System.in);
s.useDelimiter("\\R"); // Any newline symbol
int c;
do {
  // show menu here
  c = s.nextInt();
} while (c >= 1 && c <= 5);

Alternatively, you can ignore newline symbols. These are '\r' and '\n' respectively. Replace c = System.in.read(); with:

readNextChar();

.. below your main method:

public static char readNextChar() {
  while (true) {
    char c = System.in.read();
    if (c != '\r' && c != '\n') return c;
  }
}

Which will read the next char ignoring any newline symbols. (on windows, newline is '\r\n' - 2 characters in a row. On any other platform, it's just one '\n').

  • Related