2017-05-03 4 views
-9

ユーザーがNを押すまで、このコードをループする方法。「Continue?[Y/N]」という最初の完了後にプロンプ​​トを表示したい。大文字かどうかは関係ありません。それを行う方法を知っているが、firstLetters.equalsJavaコードをループする方法

package firstLast; 

import java.util.Scanner;// Imported Scanner class 

public class firstLast { 
    public static void main(String[] args) { 
     // Miwand's First Last program 
     Scanner in = new Scanner(System.in); // Insert Scanner to get input from user later on 
     String word; // The initial word 

     System.out.println("Please enter a string longer than 4 letters"); // Asking user to enter string that's more than 4 chars long 

     word = in.nextLine(); // Getting input from user 

     for() 
      String firstLetters = (word.substring(0, 2)); // Getting the first two letters 

      String lastLetters = (word.substring(word.length() - 2)); // Getting the last two letters 

      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 
      } 
      else 
      { 
       System.out.println("Different :("); // If they are different, print out this 
      } 
    } 
} 
+1

あなたは、あなたの宿題を手助けするために他の人たちが時間を費やすことを期待しています。しかし、あなたはあなたの質問のすべてを適切にフォーマット/インデントするために3分かかることはありません。 – GhostCat

+0

ヒント:後続のすべてのコメント...実際の使用はほとんどありません。そのようなラインノイズを抑えるために自分自身を鍛えてはいけません。コメントはありません** **コードは何をしていますか? **なぜ** - それがコード自体を読むことから明らかでないときだけコメントします。 – GhostCat

+0

私は、Javaループの例を見つけるのは簡単だから、この質問を議論の対象外としています。たぶんStack Overflowのドキュメントをチェックしてください。 – EJoshuaS

答えて

0
while (true) { 
    < body of the loop > 
    System.out.println("Continue? [Y/N]"); 
    String ans = in.nextLine(); 
    if (ans.toLowerCase().equals("n")) 
     break; 
    //check if y, or just loop anyway 
} 

無限forループのコードを組み込む方法がわからないイムはとにかく

編集、for(;;)です:固定「真の」真」に"

+0

whileループの真の部分をどのように修正するのですか –

+0

は@MiwandBakhtariの代わりに小文字にしてください。while(true) –

+0

そうですが、今問題は最初の文字が表示されていることです同じ継続的。私はwhileループを最初のif文の前に置く。 –

0

あなたは以下のようにこれを単純化することができますが、あなたはただ一つの条件を考慮する必要があります。 YまたはNのいずれかです。これを要件として変更できます。

Scanner sc = new Scanner(System.in); 

while (sc.nextLine().equals("Y")){ 
    // Do Stuff 
}