import java.io.*; //在测试时,这里有错误:无法解析java.util.Map$Entry.从必需的.class文件间接引用了它,怎么修改呢? import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JFrame; import javax.swing.JTextArea; public class T4 { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String fileName = "Hello.txt"; RandomAccessFile file = new RandomAccessFile(new File(fileName), "r"); String content = null; Map<String, Integer> map = new HashMap<String, Integer>(); while((content = file.readLine()) != null){ String[] ary = content.replaceAll("'|\\?|,|\\.|", "").split("\\s+"); for(String str : ary){ if(map.containsKey(str.trim())){ map.put(str, new Integer(map.get(str).intValue() + 1)); }else{ map.put(str.trim(), new Integer(1)); } } } List list = new ArrayList(); /*下面for循环显示错误:此行的多个标记- Iterator 是原始类型。应该将对通用类型 Iterator<E> 的引用参数化 -类型 Map<String,Integer> 中的方法 entrySet()引用缺少的类型 Map$Entry*/ for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Integer> element = (Map.Entry<String, Integer>) iter.next(); list.add(new WordFreq(element.getKey(), element.getValue())); } /*下面一行显示的错误是:无法解析类型 java.util.Comparator。从必需的 .class 文件间接引用了它 - Comparator 无法解析为类型 - 类型 Collections 中的方法 sort(List<T>, Comparator<? super T>)引用缺少的类型 Comparator */ Collections.sort(list, new Comparator<WordFreq>(){ public int compare(WordFreq o1, WordFreq o2) { return o1.getCount() < o2.getCount()? 1: -1; } }); int uniqueCount = 0; final StringBuilder sb = new StringBuilder(); final String NEW_LINE = "\r\n"; for(Object obj: list){ WordFreq item = (WordFreq) obj; uniqueCount += (item.getCount() == 1? 1: 0); sb.append(item.toString()); //这里显示的错误是:无法解析类型 java.lang.CharSequence 从必需的 .class 文件间接引用了它 sb.append(NEW_LINE); } JFrame f = new JFrame(); JTextArea result = new JTextArea(); result.append("Total " + list.size() + " words found in " + fileName); result.append(NEW_LINE); result.append("Total " + uniqueCount + " words appear only once"); result.append(NEW_LINE); result.append(NEW_LINE); result.append(sb.toString()); f.add(result); f.setVisible(true); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class WordFreq{ private String word; private int count; public WordFreq(String word, int count){ this.word = word; this.count = count; } public int getCount() { return count; } public String toString(){ return word + "\t" + count; } }
相关分类