2016-10-07 107 views
0

我正在掃描一個文件並試圖追蹤一個角色出現的次數。掃描字符錯誤?

public static Map<Character, Integer> getCountMap(Scanner in){ 
    Map<Character, Integer> wordCountMap = new TreeMap<Character, Integer>(); 

    while (in.hasNext()){ 
     Character word = in.next().toLowerCase(); 
     //CHAR HAS BEEN SEEN, ADD 
     if(wordCountMap.containsKey(word)){ 
      int count = wordCountMap.get(word); 
      wordCountMap.put(word, count + 1); 
     } 
     //NEW CHAR, CREATE 
     else { 
      wordCountMap.put(word, 1); 
     } 
    } 
return wordCountMap; 
} 

我得到一個錯誤Character word = in.next().toLowerCase();

我檢查的Java API,和人物肯定是要toLowerCase()訪問。然而,掃描儀的API說

hasNext() 如果此掃描程序在其輸入中有另一個標記,則返回true。

這是否意味着掃描儀無法掃描每個字符? 不應該只是掃描角色,將它們添加到地圖,並增加每次看到的東西的計數?

最後說明:如果每個Character替換爲String,此代碼運行得很好。我可以得到一個字數沒有問題。字符數,而不是太多。

主要方法(在這種情況下是必需的)

public static void main(Character[] args) throws FileNotFoundException{ 

    //read the book into the map 
    Scanner in = new Scanner(new File("moby.txt")); 
    Map<Character, Integer> wordCountMap = getCountMap(in); 


    for (Character word: wordCountMap.keySet()){ 
     int count = wordCountMap.get(word); 
     if (count > OCCURRENCES){ 
      System.out.println(word + " occurs " + count + " times."); 
     } 
    } 

} 
+0

你確定'in.next()。toLowerCase()'返回一個'Character'對象嗎? – TNT

+0

@TNT我不完全確定。我剛剛檢查了API,實際上甚至找不到in.next。我知道它適用於字符串......我在哪裏可以弄清楚這一點? 當我處理字符串時,我的掃描器(in)用下一個值填充字符串。所以也許它不需要字符... – Podo

+0

@TNT, 「The java.util.Scanner.next()方法查找並返回來自此掃描器的下一個完整標記。」 – Podo

回答

0

按照Javadocs for the next() method of java.util.Scanner

public String next() 

查找並從該掃描儀返回下一個完整標記。完整的令牌前後有與分隔符模式匹配的輸入。

可以看出,該方法不返回Character;它返回String,這就是爲什麼你會得到這個錯誤。

A 標記基本上屬於分隔符的兩個實例之間的子字符串。 Scanner的默認分隔符是空白對象(\s,\t,\n等)。因此,掃描器會遍歷該文件,並且每次調用next()都會返回介於所看到的分隔符之間的下一個字符序列。

因此,您可以做的是更改分隔符,以便掃描程序將文件中的每個字符記爲一個標記,儘管這有點複雜。你可以做的是利用String類有一個方法toCharArray(),它將字符串中的字符序列作爲數組返回。你可以很容易地計算出單個字符:

String word = in.next().toLowerCase(); 
char[] charsInWord = word.toCharArray(); 
// ... 
+0

我實際上要做一個charAt循環,但toCharArray更光滑。 – Podo