如何循环java代码

如何循环java代码,java,loops,for-loop,Java,Loops,For Loop,如何循环此代码,直到用户按N键。我希望在第一次执行后出现提示,提示“继续?[Y/N]”,无论是否为大写。我想我知道如何执行此操作,但我不确定如何合并第一个字母。equals package firstLast; import java.util.Scanner;// Imported Scanner class public class firstLast { public static void main(String[] args) { // Miwand's

如何循环此代码,直到用户按N键。我希望在第一次执行后出现提示,提示“继续?[Y/N]”,无论是否为大写。我想我知道如何执行此操作,但我不确定如何合并第一个字母。equals

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
            }
    }
}
while(true){
<循环体>
System.out.println(“是否继续?”);
字符串ans=in.nextLine();
if(ans.toLowerCase().equals(“n”))
打破
//检查是否为y,或者只是循环
}
无论如何,循环的无止境
的代码是(;;)


< >编辑:将“true”固定为“true”

,可以简化如下所示,但只需考虑一个条件。Y或N。您可以根据需要对此进行修改

Scanner sc = new Scanner(System.in);

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

叹气你期望其他人花时间帮助你做家庭作业。但是你找不到3分钟的时间来正确格式化/缩进你所有的问题。。。它们中很少有真正有用的。不要训练自己去降低这种线路噪音。不要评论代码在做什么;只评论为什么-什么时候从阅读代码本身看不明显。我投票结束这个问题,因为很容易找到Java循环的例子。也许可以查看堆栈溢出文档。它在while循环中的真实部分下面。我如何修复它?只需将其改为小写@MiwandBakhtari,就像这样
while(True)
是的,我得到了该部分,但现在的问题是,它显示的第一个字母连续不变。我将while循环放在第一个if语句canfirm之前,在java中,布尔是小写的。我的badyes@MiwandBakhtari,但它仍然不正确。它应该看起来像
,而(true){/*您的代码在这里(内部)*/}//而不是在循环外部
Scanner sc = new Scanner(System.in);

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