2017-05-03 97 views
-9

如何循環此代碼,直到用戶按下N.我想在第一次完成後提示「繼續?[是/否]」無論它是否大寫。我想我知道該怎麼做,但林不知道如何把firstLetters.equals如何循環java代碼

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循環的例子,所以我正在投票結束這個題外話題。也許檢查堆棧溢出文檔。 – 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 
}