2017-05-24 309 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; 
    } 


}