2017-05-03 73 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 
}