我正在尝试编写一个代码来计算文件中特定长度的单词数。
例如:
How are you?
会打印:
Proportion of 3-letter words: 100% (3 words)
我想计算长度为 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13+ 的单词
你能指导一下吗?
我并不是想找出单词数。我已经能够使用这段代码:
public static int WordCount() throws FileNotFoundException
{
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
count++;
}
return count;
}
我想找到一定长度的单词.
UPDATE
我编写了以下代码:
public static int WordLengthCount() throws FileNotFoundException
{
File file = new File("hello.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count5 = 0;
int hell = 0; //This is just for the else command to compile
while(keyboard.hasNext())
{
if ( keyboard.next().length() == 5 )
{
count5++;
keyboard.next();
return count5;
}
} return hell;
}