编写一个Java应用程序,使用RandomAccessFile流统计Hello.txt中的单词,要求如下: (1)计算全文中共出现了多少个单词(重复的单词只计算一次); (2)统计出有多少个单词只出现了一次; (3)统计并显示出每个单词出现的频率,
 并将这些单词按出现频率高低顺序显示在一个TextArea中

解决方案 »

  1.   

    RandomAccessFile不是很会用。。我当BufferedReader用了。。
    单词的个数就是map.size(),对应的频率都存在map的value里面public static void main(String[] args) throws IOException {
    RandomAccessFile randomAccessFile = new RandomAccessFile("aaaa.txt", "r");
    Map<String,Integer> map = new HashMap<String, Integer>();
    Pattern pattern = Pattern.compile("\\b[a-zA-z]+?\\b");
    String str = null;
    while ((str = randomAccessFile.readLine()) != null) {
    Matcher matcher = pattern.matcher(str);
    while(matcher.find()){
    String s = matcher.group();
    int count = 1;
    if(map.get(s) != null)
    count += map.get(s);
    map.put(s, count);
    }
    }
    System.out.println(map.size());
    for(Entry<String,Integer> entry : map.entrySet()){
    System.out.println(entry.getKey() + ":" + entry.getValue());
    }
    }