无限循环不起作用



代码第一次通过。但在那之后,输出不起作用。这样做的主要目标是创建一个无限循环,要求用户输入一个短语,然后是一个字母。然后,输出短语中字母的出现次数。另外 - - 我将如何通过输入单词来打破这个循环?

Scanner in = new Scanner(System.in);
for (;;) {
    System.out.println("Enter a word/phrase");
    String sentence = in.nextLine();
    int times = 0;
    System.out.println("Enter a character.");
    String letter = in.next();
    for (int i = 0; i < sentence.length(); i++) {
        char lc = letter.charAt(0);
        char sc = sentence.charAt(i);
        if (lc == sc) {
            times++;
        }
    }
    System.out.print("The character appeared:" + times + " times.");
}

删除 for 循环并将其替换为一段时间。

while 循环应检查短语,当满足该短语时,它将自动退出。

所以像

while (!phraseToCheckFor){
// your code
}

这听起来像是家庭作业,所以我不会发布所有代码,但这应该足以让你入门。

如果你需要一个无限循环,只需这样做:

for(;;) {  //or while(true) {
    //insert code here
}

可以使用 break 语句中断循环,例如:

for(;;) {
    String s = in.nextLine();
    if(s.isEmpty()) {
        break; //loop terminates here
    }
    System.out.println(s + " isn't empty.");
}

为了使程序正常运行,需要使用最后一个换行符。您可以通过添加对 nextLine 的调用来执行此操作。工作实例,

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        for (;;) {
            System.out.println("Enter a word/phrase");
            String sentence = in.nextLine();
            if (sentence.trim().equals("quit")) {
                break;
            }
            int times = 0;

            System.out.println("Enter a character.");
            String letter = in.next();
            for (int i = 0; i < sentence.length(); i++) {
                char lc = letter.charAt(0);
                char sc = sentence.charAt(i);
                if (lc == sc) {
                    times++;
                }
            }
            System.out.println("The character appeared:" + times + " times.");
            in.nextLine();//consume the last new line
        }
    }

最新更新