⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise18_7.java

📁 java程序设计 机械工业出版社 书籍代码
💻 JAVA
字号:
import java.util.*;public class Exercise18_7 {  public static void main(String[] args) {    // Text in a string    String text = "Have a good day. Have a good class. " +      "Have a good visit. Have fun!";    // Create a hash map to hold words and key and count as value    HashMap hashMap = new HashMap();    StringTokenizer st = new StringTokenizer(text, " .!?");    while (st.hasMoreTokens()) {      String key = st.nextToken();      if (hashMap.get(key) != null) {        int value = ((Integer)hashMap.get(key)).intValue();        value++;        hashMap.put(key, new Integer(value));      }      else {        hashMap.put(key, new Integer(1));      }    }    // Create a tree map from the hash map    TreeMap treeMap = new TreeMap(hashMap);    // Get an entry set for the tree map    Set entrySet = treeMap.entrySet();    // Get an iterator for the entry set    Iterator iterator = entrySet.iterator();    ArrayList list = new ArrayList();    while (iterator.hasNext()) {      StringTokenizer st1 =  new StringTokenizer(iterator.next().toString(), "=");      list.add(new WordOccurrence(st1.nextToken(),        Integer.parseInt(st1.nextToken())));    }    Collections.sort(list);    for (int i = 0; i < list.size(); i++) {      System.out.println(list.get(i));    }  }}class WordOccurrence implements Comparable {  String word;  int count;  public WordOccurrence(String word, int count) {    this.word = word;    this.count = count;  }  public int compareTo(Object o) {    return count - ((WordOccurrence)o).count;  }  public boolean equals(Object o) {    return word.equals(((WordOccurrence)o).word);  }  public String toString() {    return word + " " + count;  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -