有4行,但程序只检测到1行。 我的代码可能有什么问题?
输入文件的内容:
成为或不成为:这就是问题。
在心中是否更高尚受苦
令人发指的财富的吊索和箭头,
或者采取武器对抗麻烦的海洋。
我的代码:
import java.io.*;
import java.util.*;
public class wordcount{
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("What is the name of the file? ");
String file = console.nextLine();
Scanner input = new Scanner(new File(file));
int wordCount = 0;
while(input.hasNext()){
String word = input.next();
wordCount++;
}
int lineCount = 0;
while(input.hasNextLine()){
String line = input.nextLine();
lineCount++;
}
System.out.println("total words = " + wordCount);
System.out.println("total lines = " + lineCount);
}
}
答案 0 :(得分:10)
你的第一个while
循环正在消耗整个文件,然后除了最后的换行之外什么都没有了。相反,将您的顶级循环设置为行计数器,并在每次迭代中拆分空格,标记化或扫描该行以查找单词数:
while(input.hasNextLine()) {
String line = input.nextLine();
lineCount++;
wordCount += line.split("\\s+").length;
}
答案 1 :(得分:1)
在两个for-loops
之间添加此行:
input = new Scanner(new File(file)); /* get a new scanner to start over */
扫描仪从头到尾读取,耗尽输入。我没有看到将扫描仪指针重置为文件开头的方法(Scanner.reset()
没有这样做)。