【问题标题】:Java 'Skips' on .equals Statement.equals 语句上的 Java“跳过”
【发布时间】:2013-08-29 18:14:47
【问题描述】:

我的 java 程序,以及下面显示的部分,似乎卡在 if("".equals) 行。虽然 if 语句中的选项都没有运行,但 while 循环继续继续。因此,它不是打印出新数据(在 else 下)或打印出信息(在默认 if 下),而是不断要求新的输入。

        System.out.println("Type in government type. Enter '?' and click enter for list of gov types.");
        while(playerSelection==false);
        {
            input = fileinput.nextLine();
            if("?".equals(input))
            {
                System.out.println("despotic_monarchy, administrative_monarchy, constitutional_monarchy, despotic_monarchy, enlightened_despotism, feudal_monarchy, revolutionary_empire\n"+
                    "administrative_republic, beauracratic_despotism, constitutional_republic, republican_dictatorship, merchant_republic, noble_republic, revolutionary_republic\n"+
                    "papal_government\n"+
                    "steppe_horde, tribal_democracy, tribal_despotism, tribal_federation");
            }
            else
            {
                fileLines[lGov[nationSelected]] = "     " + input;
                System.out.println(fileLines[lGov[nationSelected]]);
                playerSelection=true;
            }
        }

【问题讨论】:

    标签: java string if-statement equals


    【解决方案1】:

    while 语句后面紧跟一个分号,Java 会将其视为while 循环的整个主体,从而导致无限循环。然后它永远不会到达它下面的大括号中的块。

    删除分号,因此您想要的大括号中的块实际上是while 循环块。

    【讨论】:

    • 另一个让我抓狂的 java 特质。为什么空白语句不能抛出编译错误?
    • @Cruncher 一个好的 IDE 会给你一个警告,告诉你你的 while 循环是空的。 IntelliJ 突出显示它,说“'while' 循环有空体”。即便如此,不幸的是,它是合法的 Java,即使它令人惊讶。
    • @rgettman 我使用 jGrasp。此外,现在它似乎完全跳过了我的 nextLine() 语句,然后运行 ​​else 行并退出 while 而不从用户那里得到任何输入。注释掉 playerSelection==true;它是否运行正确,尽管它似乎在请求输入之前运行了一次 while 循环,因为它跳过了一行(我可以假设是 else 中的打印)。
    • @Cruncher Why can't blank statements throw a compile error? 它们有合法用途,例如在方法String.indexOf(): while (++i <= max && source[i] != first);
    • 好吧,至于我的第二个问题,我不太确定为什么它似乎会立即接受一个空白字符串 "" 作为输入,所以我只是为 "" 添加了一个 elseif,它什么都不做。添加后工作正常。再次感谢 rgett。编辑:(另外,对于问我之前是否有 nextInt 的人,是的,我有。出于某种原因,您的评论显示在我的收件箱中,但没有显示在页面上。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多