2017-05-24 375 views
0

当下面的代码是真实的,这意味着在第一和最后一个字符匹配的持续循环,直到我退出了代码,如何解决呢?如何停止无限while循环

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

你永远不更新'firstLetters'和'lastLetters'。 –

+0

对不起,你的意思是?进出口新的这 – impassedKF

+0

他表示说他们从来没有改变过。 –

回答

0

无处在你的代码你有更新的firstLetterslastLetters变量,因此相同的检查,反复执行。

如果你想避免的,而(真),打破需要,可以指定在while循环定义本身你的休息条件...只是一个想法。

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)) 

您还需要System.out.println("Different :(");后完成} else,所以用户总是问他们是否想进入另一个词。事实上,你只问他们,如果这些话是不同的。

0

只是把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; 
} 
+0

但是,如果我这样做,那么它去再次询问用户是否要继续使用程序 – impassedKF

+0

把问出来的,如果别的。意思是询问用户,不管他的结果如何 –

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


}