2017-05-24 12 views
0

以下のコードが真の場合、最初と最後の文字が一致すると、コードを終了するまで永遠にループします。あなたのコード内のどこにもループを無限に停止する方法

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

:その場合は、あなたがもし-else文の外に質問を配置する必要があり、その後、ロジックはこのような何かを行く必要があります。 –

+0

申し訳ありませんが、どういう意味ですか?私はこれに新しいです – impassedKF

+0

彼は彼らが決して変更されないことを意味します。 –

答えて

0

あなたはfirstLetterslastLetters変数への更新を持っていないため、同じチェックが繰り返し実行されます。

while(真)およびブレークの必要性を避けたい場合は、whileループ定義自体にブレーク基準を指定できます。単なる考えです。

0

あなたは、いくつかのより多くのコードを追加する必要があります - あなたはまた、System.out.println("Different :(");} elseを終了する必要があるので、彼らは別の単語を入力したい場合は、ユーザーが常に求められている

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

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

を。そうであるように、言葉が違うかどうかだけを尋ねます。

0

メッセージ

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

を印刷した後、あなたがここで何をしたいのかを理解することは困難である場合だけ最初にbreak文を入れました。私はあなたが彼が終了したい時まで、チェックされるべき単語を入力するようにユーザに依頼し続けたいと思う。あなたが `firstLetters`と` lastLetters`を更新したことがない

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


} 
関連する問題