【问题标题】:While loop with String comparing isn't working?带有字符串比较的循环不起作用?
【发布时间】:2020-07-30 17:31:37
【问题描述】:

我刚开始学习 Java...对不起,如果这只是一个太愚蠢的问题。

我试图比较用户输入。如果输入不是“是”或“否”,则强制用户输入其中任何一个...但我的代码不起作用...

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

尝试在循环中打印出“userInput”的值,但输入时正确显示“是”或“否”,但循环仍在继续。

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;
    }

关于如何修复此代码的任何想法?

【问题讨论】:

  • 检查 do-while 循环
  • !userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No") 始终为真。

标签: java string compare


【解决方案1】:

!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No") 始终为真,因为Yes 不是No 并且No 不是Yes

当输入不是Yes并且不是No时,你会想要循环,所以条件应该是!userInput.equalsIgnoreCase("Yes") && !userInput.equalsIgnoreCase("No")

【讨论】:

  • 哦,我明白了!非常感谢你!该死,我确实需要更多的练习。大声笑
猜你喜欢
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 2017-08-13
  • 2014-04-03
  • 2012-01-22
  • 2017-12-07
相关资源
最近更新 更多