简体   繁体   中英

why does it not break out of the loop whatever is the input

whatever the input is, it never breaks the loop i tried.

i tried with the switch same result; i tried with only one condition (.answer.equalsIgnoreCase("y")) without the OR and it worked but nott with two conditions.

public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);


    //checking if the dog is barking
    System.out.println("is the dog is barking ?");
    String answer;
    do {
        System.out.println("write 'n' for no and 'y' for yes");
        answer = scn.next();
    } while( !answer.equalsIgnoreCase("y") || !answer.equalsIgnoreCase("n"));
    boolean dogBark=answer.equalsIgnoreCase("y");

i expect it to finish the while loos as soon as i enter 'y' or 'n' but its asks me for input over and over.

While answer is not yes or answer is not no?

If it's yes, then it isn't no. If it's no, then it isn't yes. So the condition is always true and it loops.

You probably want to use the ! operators.

while( !answer.equalsIgnoreCase("y") || !answer.equalsIgnoreCase("n"));

The issue is occurring because the do-while loop is checking both conditions with the OR statement.

Think about it like this, if Answer equals "Y" that condition is met to break the loop but the OR condition "N" is still active therefore the loop will continue.

The do while is only checking to ensure one of the conditions above is false before continuing the loop.

To fix this replace the || with && and the loop will break if either Y or N is entered as the loop will only continue if both conditions are false.

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