簡體   English   中英

文字分析Word Counter Java

[英]Text analysis Word Counter Java

我需要編寫讀取和執行文件文本分析的代碼。 它需要做的一件事是計算文件中有多少個單詞。 我寫了一個方法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);


}

嘗試這個?

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

為您的計數詞方法聲明一個新的掃描器,問題出在s.next();下。 它會讀取緩沖區中的下一個單詞並丟棄前一個單詞,因此在調用最長單詞方法之后,掃描程序緩沖區已用完。

您已經閱讀了掃描儀,然后再次閱讀。 只需創建另一個掃描儀以數字法使用

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

之前

 countWords(fileScanner);

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM