【问题标题】:why cant i get out of this while loop? [duplicate]为什么我不能摆脱这个while循环? [复制]
【发布时间】:2014-05-27 14:05:54
【问题描述】:

我们的项目主要涉及读取有关英超联赛的文件并返回 1. 比赛结果、2. 尚未比赛的赛程和 3. 排行榜(表格)。我在命令行中显示一个菜单,并从那里接受用户输入。我正在使用 while 循环将用户输入与要显示的输出相匹配,但我想说如果他们不输入 1,2 或 3 则表示有错误并再次显示菜单并要求他们输入另一个输入。但是现在如果我输入 1,2 或 3,它不会显示我的结果,我无法退出 while 循环。谁能帮我?这是我的代码!

while(userInput == false)
    {
        Scanner input = new Scanner(System.in);
        String pattern = "[1-3]{1}";
        String userChoice;
        System.out.println(menuOptions);
        userChoice = input.nextLine();
        if(userChoice == "1")
        {
            System.out.print(outcomesResults);
            userInput = true;
        }
        if(userChoice == "2")
        {
            System.out.print(fixturesResults);
            userInput = true;
        }
        if(userChoice == "3")
        {
            System.out.print(leaderboardResults);
            userInput = true;
        }
        else if(!userChoice.matches(pattern))
        {
            System.out.println();
            System.out.println("Error: unidentified selection. Please choose 1,2 or 3");
            userInput = false;
        }
    }

【问题讨论】:

  • userchoice.equals("1")

标签: java loops input while-loop


【解决方案1】:

如果你想比较String值,你应该使用equals():

if (userChoice.equals("1")) {
   // do something
}

【讨论】:

    猜你喜欢
    • 2014-03-28
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多