使用带字符串/整数关系的hashMaps

时间:2015-03-30 15:15:50

标签: java string hashmap entryset

我遇到了一些当前代码的问题。我完成了上半部分,但现在我使用hashMap搜索导入的文本文档,找到最常用的单词及其出现的次数。我写了很多语法,我的教授说这有点无关紧要,所以我把它削减了一些。我遇到的问题是使用entrySet,我们必须使用它。我已经到了这一点,但我遇到了实施它的问题。任何帮助都会很棒,我只是不熟悉entrySet概念,但我已经阅读了文档。

谢谢,这是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class HashMapPractice {

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

    Scanner file = new Scanner(new File("crime_and_punishment.txt"));

    Map<String, Integer> crimeMap= new HashMap<String, Integer>();

    while (file.hasNext()){
        String word = file.next();
        if(crimeMap.containsKey(word)){
            int placeholder = crimeMap.get(word) + 1;
            crimeMap.put(word, placeholder);
        }else{
            crimeMap.put(word, 1);
        }   
    }//ends while loop

    Set<Map.Entry<String,Integer>> entrySet = crimeMap.entrySet();


    for(Map.Entry<String, Integer> ent : entrySet){
        String key = ent.getKey();
        Integer value = ent.getValue();

        System.out.printf("Word: [" + ent.getKey()+"], Times: ["  +   

         ent.getValue()+"]");
    }
}//ends main
}//ends class

0 个答案:

没有答案