简体   繁体   English

如何逃避while循环

[英]How to escape this while-loop

I wrote the following method, which boolean-return type is again assigned to another boolean in another method in which I call this method. 我编写了以下方法,该布尔返回类型再次分配给另一个方法中的另一个布尔,在该方法中我将此方法称为该方法。

    private boolean answer() {

    Scanner input = new Scanner(System.in);
    boolean b = false;
    String answer = input.nextLine();

    while(answer != "y" || answer != "n") {
        System.out.println("Answer with y (yes) or n (no)");
        answer = input.nextLine();
    }
    if (answer == "y") {
        b = true;
    }
    return b;

}

But no matter what I type in (y, n, or any other letter), I always end up in the while-loop again. 但是无论我输入什么(y,n或任何其他字母),我总是总是再次进入while循环。

It's because you have an or rather than and on your test. 这是因为您在测试中具有or而不是and

As it's currently coded you are saying: 正如目前所编码的那样,您在说:

while the answer isn't "y" or it isn't "n", loop. 当答案不是“ y” 不是“ n”时,循环。

which will always be the case. 情况总是如此。

What you want is: 您想要的是:

while the answer isn't "y" and it isn't "n", loop. 答案不是“ y” 不是“ n”时,循环。

which is coded as: 编码为:

while (answer != "y" && answer != "n") (

更改为: while(answer != "y" && answer != "n") ,您的代码将按预期工作。

I suspect your problem lies here: while(answer != "y" || answer != "n") 我怀疑您的问题出在这里:while(answer!=“ y” || answer!=“ n”)

When your answer = "y" it isn't = "n" so the loop continues and vice verse. 当您的答案=“ y”时,它不是“ n”,因此循环继续进行,反之亦然。

Probably you want this: while(answer != "y" && answer != "n") 可能您想要这样:while(answer!=“ y” && answer!=“ n”)

I changed your code a bit to accept a char instead. 我稍微更改了您的代码以接受一个char。

Here is the code: 这是代码:

private boolean answer() {

    Scanner input = new Scanner(System.in);
    boolean b = false;

    char answer = input.nextLine().toLowerCase().charAt(0);

    while(answer != 'y' || answer != 'n' ) {
        System.out.println("Answer with y (yes) or n (no)");
        //lower case so that it will get y or n, no matter what the casing is
        answer = input.nextLine().toLowerCase().charAt(0);
    }
    if (answer == 'y') {
        b = true;
    }
    return b;

}

or if you really want a string 或者如果您真的想要一个字符串

private boolean answer() {

    Scanner input = new Scanner(System.in);
    boolean b = false;
    String answer = input.nextLine();

    while( !(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")) ) {
        System.out.println("Answer with y (yes) or n (no)");
        answer = input.nextLine();
    }
    if (answer.equalsIgnoreCase("y")) {
        b = true;
    }
    return b;
}

Remember to use .equals() or .equalsIgnoreCase() when comparing two Strings 比较两个字符串时,请记住使用.equals().equalsIgnoreCase()

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

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