While循环与字符串比较不起作用?

huangapple go评论42阅读模式
英文:

While loop with String comparing isn't working?

问题

我刚开始学习Java...如果这个问题太愚蠢的话请原谅。

我试图比较用户输入。如果输入既不是“是”也不是“否”,那么强制用户输入其中之一...但我的代码不起作用...

编译没有问题,但即使输入是“是”或“否”,while循环也继续循环。

尝试在循环内打印“userInput”的值,但当输入时它显示“是”或“否”,但循环仍然继续。

protected static boolean askUser() {
    String userInput = "x";
    boolean userChoice;
    System.out.println("你是否有问题想要知道答案? (是/否):");
    userInput = input.nextLine();

    while (!userInput.equalsIgnoreCase("是") && !userInput.equalsIgnoreCase("否")) {
        System.out.println("请只输入“是”或“否”:");
        userInput = input.nextLine();
    }

    if (userInput.equalsIgnoreCase("是")) {
        userChoice = true;
    } else {
        userChoice = false;
    }

    return userChoice;
}

如何修复这段代码?

英文:

I just started learning Java... Sorry if this is just a way too dumb question.

I was trying to compare the user input. If the input is not either "Yes" or "No" then force the user to input either one of them... but my code don't work...

Compiling has no issue, but even if the input is "Yes" or "No" the while loop just keep looping.

Tried printing out the value of "userInput" within the loop but it shows "Yes" or "No" correctly when inputted, yet the loop just goes on.

protected static boolean askUser() {
        String userInput = "x";
        boolean userChoice;
        System.out.println("Do you have a question you want to know the answer too? (Yes/No): ");
        userInput = input.nextLine();

        while (!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No")) {
            System.out.println("Please input only \"Yes\" or \"No\": ");
            userInput = input.nextLine();
        }

        if (userInput.equalsIgnoreCase("Yes")) {
            userChoice = true;
        } else {
            userChoice = false;
        }

        return userChoice;
    }

Any idea on how to fix this code?

答案1

得分: 5

!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No") 始终为真,因为 Yes 不等于 NoNo 不等于 Yes

您需要在输入既不是 Yes 不是 No 的情况下循环,所以条件应为 !userInput.equalsIgnoreCase("Yes") && !userInput.equalsIgnoreCase("No")

英文:

!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No") is always true because Yes is not No and No is not Yes.

You will want to loop while the input is not Yes and not No, so the condition should be !userInput.equalsIgnoreCase("Yes") && !userInput.equalsIgnoreCase("No").

huangapple
  • 本文由 发表于 2020年7月31日 01:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63178395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定