对于循环只运行一次

Sol*_*cid -1 java for-loop

我正在尝试一个for循环的代码片段,用户输入他将要写的单词数,然后输入单词本身,最后它应该检查特定的要求(用K开始的单词增加计数值以及以K开头的最后一个单词将被注册).但是由于某些原因我不知道,它只是不会循环,无论输入它只打印出代码上的所有内容.

package Others;
import java.util.*;
public class StartsWithString 
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        int wordNumber = 0;
        String words = "";
        int wordCount = 0;
        String lastWord = "";

        System.out.println("How many words are you going to write?: ");
        wordNumber = sc.nextInt();

        System.out.println("Write the desired words: ");
        for(int i = 0; i < wordNumber; i++);
        {
            words = sc.nextLine();

            if(words.startsWith("K"))
            {
                wordCount++;
                lastWord = words;
            }
        }

        System.out.println("From a total of " + numriFjaleve + " words typed,);
        System.out.println(wordCount + " started with the letter K.");
        System.out.println("The last word typed which began with the letter K was: " + lastWord);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*Kon 11

for(int i = 0; i < wordNumber; i++);
Run Code Online (Sandbox Code Playgroud)

循环定义结束时有一个分号.所以你的循环实际上不是一个循环.这是一个独立code block运行一次.删除分号.

  • 我的Eclipse显示一个黄色标记,工具提示"Empty control-flow statement".---我看过太多这个错误的例子,这是我更喜欢行尾的起始大括号的原因之一,而不是它自己的行.减少错误的可能性,不要浪费代码行.但我知道这可能是一个政策问题. (3认同)
  • @Solocid 这是一个常见错误,不用担心。您的 IDE 应该用一些警告来标记它,但一般来说,您只是擅长在不应该出现的地方发现分号。你的眼睛会自动调整。 (2认同)