如何停止无限循环

时间:2017-05-24 13:18:05

标签: java loops while-loop

当下面的代码为真时,意味着当第一个和最后一个字符匹配时,它会永远循环,直到我退出代码,我该如何修复它?

while (true) {
    // Ignores case and checks if the firstLetters and lastLetters are the same
    if (firstLetters.equalsIgnoreCase(lastLetters)) 
    {
        // if they are then print out this
        System.out.println("The first two letters and the last two are the same!");
    }
    else
    {   
        System.out.println("Different :("); // If they are different print out this
        System.out.println("Continue? [Y/N]");
        String ans = in.nextLine();
        System.out.println("Please enter a string longer than 4 letters");
        word=in.nextLine();
        // Ignores case and checks if the firstLetters and lastLetters are the same
        if (firstLetters.equalsIgnoreCase(lastLetters)) 
        {
            break;
        }
    }
}

4 个答案:

答案 0 :(得分:0)

您的代码中没有任何地方对firstLetterslastLetters变量进行更新,因此会重复执行相同的检查。

如果你想避免while(true)和break需求,你可以在while循环定义中指定你的中断标准......只是一个想法。

答案 1 :(得分:0)

您需要添加更多代码: -

word=in.nextLine();
// New code
firstLetters = word.substring(0, 1);
lastLetters = word.substring(word.length()-1, 1);

// As you were...
if (firstLetters.equalsIgnoreCase(lastLetters))

您还需要在} else之后完成System.out.println("Different :(");,因此系统会询问用户是否要输入其他字词。事实上,你只会问他们这些词是否不同。

答案 2 :(得分:0)

在打印消息后,只需在第一个中添加一个break语句

SqlTransaction

答案 3 :(得分:0)

很难理解你想在这里做什么。我想你一直要求用户输入要检查的单词,直到他想退出为止。如果是这种情况,那么你应该把问题放在if-else语句之外,逻辑应该是这样的:

while (true) {
    // Get the word
    System.out.println("Please enter a string longer than 4 letters");
    word=in.nextLine();

    // Get the letters
    firstLetters = word.substring(0, 1);
    lastLetters = word.substring(word.length()-1, 1);

    // Ignores case and checks if the firstLetters and lastLetters are the same
    if (firstLetters.equalsIgnoreCase(lastLetters)) 
    {
        // if they are then print out this
        System.out.println("The first two letters and the last two are the same!");
    }
    else
    {   
        System.out.println("Different"); // If they are different print out this
    }

    // Asks  the user if he wnats to keep inputing words
    System.out.println("Continue? [Y/N]");
    String ans = in.nextLine();

    // The user wants to quit, breaks from the loop
    if(ans.equals("N")){
         break;
    }


}