简体   繁体   English

为什么它不跳出循环无论输入是什么

[英]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.我只尝试了一个条件 (.answer.equalsIgnoreCase("y")) 没有 OR 并且它有效但不适用于两个条件。

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.我希望它在我输入“y”或“n”后立即完成 while loos,但它一遍又一遍地要求我输入。

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.出现此问题是因为 do-while 循环正在使用 OR 语句检查这两个条件。

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.这样想,如果 Answer 等于“Y”,则满足条件以中断循环,但 OR 条件“N”仍处于活动状态,因此循环将继续。

The do while is only checking to ensure one of the conditions above is false before continuing the loop. do while 仅在继续循环之前检查以确保上述条件之一为假。

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.&&并且如果输入 Y 或 N 循环将中断,因为只有两个条件都为假时循环才会继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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