简体   繁体   中英

Text analysis Word Counter Java

I need to write code that reads and does a text analysis of a file. One of the things it needs to do is to count how many words there are in the file. I wrote a method countWords , but when I run the program it returns 0. The text file I am using contains the following:

Ask not what your country can do for you ask what you can do for your country

So it clearly should return 17 and not 0. What did I do wrong?

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);


}

try this?

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);
}

Declare a new scanner for your count words method, the problem lies under s.next(); it reads the next word in your buffer and discard the previous ones, so after you called your longest word method, the scanner buffer has been used up.

You already read the scanner and reading it again. just create another scanner to use in count words method

 fileScanner = new Scanner(<your file object>);

before

 countWords(fileScanner);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM