I think the title is self explanatory. I'm trying to print how many words are in each line of a text file, the following is what I have so far:
我认为标题是自我解释的。我正在尝试打印文本文件的每一行中有多少单词,以下是我到目前为止的内容:
package filereader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordNumberer
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("story.txt");
Scanner scanner = new Scanner(file);
int wordCount = 0;
while (scanner.hasNextLine())
{
while (scanner.hasNext())
{
wordCount += 1;
System.out.println(wordCount);
}
}
scanner.close();
}
}
2 个解决方案
#1
1
You should print the result outside of second while loop and you need to reset count before you start counting for next line.
您应该在第二个while循环之外打印结果,并且需要在开始计算下一行之前重置计数。
while (scanner.hasNextLine()){
while (scanner.hasNext()){
wordCount += 1;
}
System.out.println(wordCount);
wordCount = 0;
}
#2
0
while (scanner.hasNext())
is an infinite loop if you don't consume the next token, you have the same problem with while (scanner.hasNextLine())
if you don't consume the line .
while(scanner.hasNext())是一个无限循环,如果你不使用下一个标记,如果你不使用该行,则while(scanner.hasNextLine())会遇到同样的问题。
Other than that, as other people already pointed pout, you should print the count only at the end of the line, then reset the counter to 0.
除此之外,正如其他人已经指出pout,你应该只在行的末尾打印计数,然后将计数器重置为0。
while (scanner.hasNextLine())
{
while (scanner.hasNext())
{
wordCount += 1;
scanner.next();// consume token
}
System.out.println(wordCount);// print count for the current line
wordCount = 0; // reset counter
scanner.nextLine();//consume line
}
#1
1
You should print the result outside of second while loop and you need to reset count before you start counting for next line.
您应该在第二个while循环之外打印结果,并且需要在开始计算下一行之前重置计数。
while (scanner.hasNextLine()){
while (scanner.hasNext()){
wordCount += 1;
}
System.out.println(wordCount);
wordCount = 0;
}
#2
0
while (scanner.hasNext())
is an infinite loop if you don't consume the next token, you have the same problem with while (scanner.hasNextLine())
if you don't consume the line .
while(scanner.hasNext())是一个无限循环,如果你不使用下一个标记,如果你不使用该行,则while(scanner.hasNextLine())会遇到同样的问题。
Other than that, as other people already pointed pout, you should print the count only at the end of the line, then reset the counter to 0.
除此之外,正如其他人已经指出pout,你应该只在行的末尾打印计数,然后将计数器重置为0。
while (scanner.hasNextLine())
{
while (scanner.hasNext())
{
wordCount += 1;
scanner.next();// consume token
}
System.out.println(wordCount);// print count for the current line
wordCount = 0; // reset counter
scanner.nextLine();//consume line
}