Java 如何停止无限循环

Java 如何停止无限循环,java,loops,while-loop,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

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

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

您的代码中没有任何地方更新了
firstLetters
lastLetters
变量,因此重复执行相同的检查


如果要避免while(true)和break需要,可以在while循环定义本身中指定break条件。。。只是想一想。

您需要添加更多代码:-

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

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

您还需要在
System.out.println(“Different:(“”;
)之后完成
}else
,因此用户总是被询问是否要输入另一个单词。事实上,您只会问他们单词是否不同。

在打印消息后的第一个if中添加一个break语句即可

if (firstLetters.equalsIgnoreCase(lastLetters)) //Ignores case and checks if the firstLetters and lastLetters are the same
{
    System.out.println("The fist two letters and the last two are the same!");//if they are than print out this
    break;
}

很难理解你想在这里做什么。我想你想一直要求用户输入要检查的单词,直到他想退出。如果是这样,那么你应该把问题放在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;
    }


}

你从未更新过
第一个字母
最后一个字母
。对不起,你的意思是什么?我是新来的,意思是它们从未更改过。你想做什么,你能详细解释一下吗?但是如果我这样做了,它会再次询问用户是否想继续使用该程序。将询问排除在“如果其他”之外。意思是问用户regar不顾他的结果