簡體   English   中英

計算文本文件中的特定單詞-Java

[英]Count specific words from text file - Java

我有一個文本文件,我想計算已定義的特定單詞的總數。

我的代碼:

    String word1 = "aa";
    String word2 = "bb";

    int wordCount = 0;

     //creating File instance to reference text file in Java
    File text = new File("D:/project/log.txt");

    //Creating Scanner instnace to read File in Java
    Scanner s = new Scanner(text);

    //Reading each line of file using Scanner class
    while (s.hasNext()) {
        totalCount++;
        if (s.next().equals(word1) || s.next().equals(word2)) wordCount++;
    }

    System.out.println("Word count:  " + wordCount);

但是,它僅計算“ aa”的數量。 它不計算“ bb”的數量。 可能是什么問題呢?

就像其他人所說的:您兩次調用next()的問題根源。 只是提示如何使您的算法易於擴展:

Set<String> words = new HashSet<>(Arrays.asList("aa", "bb"));
...
while (s.hasNext()) {
    totalCount++;
    if (words.contains(s.next())) wordCount++;
}

您在if條件中兩次調用s.next() ,每次調用都移至下一個單詞。 將您的while循環更改為

while (s.hasNext()) {
    totalCount++;
    String word = s.next();
    if (word.equals(word1) || word.equals(word2)) wordCount++;
}

嘗試這種方式:

while (s.hasNext()) {
    totalCount++;
    String word = s.next()
    if (word.equals(word1) || word.equals(word2)) wordCount++;
}

每次調用s.next() ,它都會找到下一個單詞,因此每個循環都在測試一個單詞是“ aa”還是下一個單詞是“ bb”。 在循環中,您將需要調用s.next() ,將結果存儲在變量中,然后使用兩個單詞進行檢查。

您的問題是您兩次調用s.next() 每個調用都會從輸入中讀取一個新令牌。

將其更改為:

while (s.hasNext()) {
    String str = s.next();
    totalCount++;
    if (str.equals(word1) || str.equals(word2)) wordCount++;
}

您在if條件中兩次調用next()。

嘗試:

String word = s.next();

if ( word.equals(word1) ....
    String[] array = new String[]{"String 1", "String 2", "String 3"};

    for(int i=0; i < array.length; i++)
     {
                    System.out.println(array[i]);
                    wordCount=0;
                    while (s.hasNext()) 
                     {
                         totalCount++;
                         if (s.next().equals(array[i])) 
                         wordCount++;
                     }
                     System.out.println("each Word count:  " + wordCount);
     }

暫無
暫無

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

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