简体   繁体   中英

Scanner in a while loop, loop won't quit

I want to get input from the user which is either 1 or 2 and propmpt the user for the answer again if he doesn't comply with the right answer.

I tried doing it with a while loop:

    int players = 0;
    players = sc.nextInt();

    while (players != 1 || players != 2)
    {
        System.out.println("Wrong input, choose again:");
        players = sc.nextInt();
        System.out.println(players);
    }

and a do-while:

    do
    {
        players = sc.nextInt();
    }
    while (players != 1 || players!= 2);

But the loop never quits, even when I input the right number.

And this logic used to work with scanf in C.

players != 1 || players != 2

this condition is always true. || means or . So the expression is true if at least one of its two operands is true

  • if players is 1, then players != 2 is true, so the whole expression is true
  • if players is 2, then players != 1 is true, so the whole expression is true
  • if players is anything else, then both expressions are true.

You want && , not || .

players != 1 || players!= 2 players != 1 || players!= 2 is always true and should be players != 1 && players!= 2 . I seriously doubt this wrong logic worked with C !

If you know a little about boolean algebra, you must know that not(not(A) or not(B)) <=> A and B . In your case, it means that the negation of your condition (which must be true for the loop to exit) is players == 1 && players == 2 , which is trivially impossible.

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