这段代码为什么读文本文档的行数和字数结果都打印出来是0?
public class Example{
public static void main(String[] args){
statistics();
}
public static void statistics(){
try{
Scanner in = new Scanner(new File("health.txt"));
int characters = 0, words = 0, lines = 0;
String word = "";
while (in.hasNextLine()){
in.nextLine();
lines++;
}
in = new Scanner(new File("health.txt"));
while(in.hasNext()){
in.next();
words++;
}
in = new Scanner(new File("health.txt"));
while(in.hasNext()){
word = in.next();
characters = characters + word.length();
}
System.out.println("No. of charcters: " + characters);
System.out.println("No. of words: " + words);
System.out.println("No. of lines: " + lines);
}
catch(Exception exception){
System.out.print(exception.getMessage());
}
}
}
该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
您的代码中存在一个问题,即在第一个while
循环中,虽然计算了文件的行数,但是没有将文件指针重新定位到文件开头,导致后续的读取操作都是从文件末尾开始的,因此行数、字数和字符数都被计算为0。
解决方法是在第一个while
循环结束后,使用in.close()
关闭文件,然后重新打开文件并将文件指针重新定位到文件开头,然后进行后续的读取操作。修改后的代码如下:
public static void statistics(){
try{
Scanner in = new Scanner(new File("health.txt"));
int characters = 0, words = 0, lines = 0;
String word = "";
while (in.hasNextLine()){
in.nextLine();
lines++;
}
in.close(); // 关闭文件
in = new Scanner(new File("health.txt"));
while(in.hasNext()){
in.next();
words++;
}
in.close(); // 关闭文件
in = new Scanner(new File("health.txt"));
while(in.hasNext()){
word = in.next();
characters = characters + word.length();
}
in.close(); // 关闭文件
System.out.println("No. of charcters: " + characters);
System.out.println("No. of words: " + words);
System.out.println("No. of lines: " + lines);
}
catch(Exception exception){
System.out.print(exception.getMessage());
}
}
这样修改后,就可以正确计算文件的行数、字数和字符数了。
如果以上回答对您有所帮助,点击一下采纳该答案~谢谢
文件名带上完整路径看看,是不是没有找到那个对应的文件。