我正在尝试从用户那里获取输入,并打印文本文件中的行数、单词数和字符数。但是,只有字数是正确的,它总是为行和字符打印 0。
import java.util.*;
import java.io.*;
public class TextFileInfoPrinter
{
public static void main(String[]args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.println("File to be read: ");
String inputFile = console.next();
File file = new File(inputFile);
Scanner in = new Scanner(file);
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNext())
{
in.next();
words++;
}
while(in.hasNextLine())
{
in.nextLine();
lines++;
}
while(in.hasNextByte())
{
in.nextByte();
chars++;
}
System.out.println("Number of lines: " + lines);
System.out.println("Number of words: " + words);
System.out.println("Number of characters: " + chars);
}
}