我试图从用户那里获取输入,并在文本文件中打印行数,单词和字符.但是,只有单词的数量是正确的,它总是为行和字符打印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);
}
}