文本分析字计数器Java

文本分析字计数器Java,java,word-count,Java,Word Count,我需要编写代码来读取并对文件进行文本分析。它需要做的一件事是计算文件中有多少单词。我编写了一个方法countWords,但当我运行程序时,它返回0。我正在使用的文本文件包含以下内容: 不要问你的国家能为你做些什么 问问你能为你的国家做些什么 因此,它显然应该返回17,而不是0。我做错了什么 public class TextAnalysis { public static void main (String [] args) throws IOException { File in01

我需要编写代码来读取并对文件进行文本分析。它需要做的一件事是计算文件中有多少单词。我编写了一个方法
countWords
,但当我运行程序时,它返回0。我正在使用的文本文件包含以下内容:

不要问你的国家能为你做些什么 问问你能为你的国家做些什么

因此,它显然应该返回17,而不是0。我做错了什么

public class TextAnalysis {

public static void main (String [] args) throws IOException {
    File in01 = new File("a5_testfiles/in01.txt");
    Scanner fileScanner = new Scanner(in01);

    System.out.println("TEXT FILE STATISTICS");
    System.out.println("--------------------");
    System.out.println("Length of the longest word: " + longestWord(fileScanner));
    System.out.println("Number of words in file wordlist: " );
    countWords(fileScanner);


}

public static String longestWord (Scanner s) {
    String longest = "";
    while (s.hasNext()) {
        String word = s.next();
        if (word.length() > longest.length()) {
            longest = word;
        }
    }

    return (longest.length() + " " + "(\"" + longest + "\")");
}

public static void countWords (Scanner s) throws IOException {
    int count = 0;

        while(s.hasNext()) {
            String word = s.next();
                count++;
        }

    System.out.println(count);


}

为count words方法声明一个新的扫描器,问题在于s.next();它读取缓冲区中的下一个单词,并丢弃上一个单词,因此在调用最长单词方法后,扫描仪缓冲区已用完。

您已读取扫描仪并再次读取。只需创建另一个扫描器,用于计数单词的方法

 fileScanner = new Scanner(<your file object>);
希望这有帮助。

试试这个

void countWords()
{
          String temp;
          File path = new File("c:/Bala/");//give ur path
          File file = new File(path, "Bala.txt");//give ur filename
          FileReader fr = new FileReader(file);
          char cbuf[] = new char[(int) file.length()];
          fr.read(cbuf);
          temp = new String(cbuf);
          String count[]=test.split("\\s");
          System.out.println("Count:"+t.length);
}

不要重复使用扫描仪。什么是
longestWord(扫描仪)
,输出很棒。。享受编码乐趣:)
void countWords()
{
          String temp;
          File path = new File("c:/Bala/");//give ur path
          File file = new File(path, "Bala.txt");//give ur filename
          FileReader fr = new FileReader(file);
          char cbuf[] = new char[(int) file.length()];
          fr.read(cbuf);
          temp = new String(cbuf);
          String count[]=test.split("\\s");
          System.out.println("Count:"+t.length);
}