我正在尝试一个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);
}
}
答案 0 :(得分:11)
for(int i = 0; i < wordNumber; i++);
循环定义结束时有一个分号。所以你的循环实际上不是一个循环。这是一个独立的code block
,运行一次。删除分号。