输出《Harry Potter and the Sorcerer's Stone》文本中的前N个最长用的英文单词及其数量
实验思路:
1. 利用输入流将文件当中内容读入。
2. 将文件内容存入StringBuffer中;
3. 利用String的split()方法将字符串分隔,并将其存入数组中;
4. 遍历数组将其存入Map<String, Integer>中
5. 利用Collections的sort()方法进行排序。
6.输出打印。
import java.io.*; import java.util.*; import java.util.Map.Entry; public class two { public static int n=0; public static void main(String[] args) { Scanner input=new Scanner(System.in); int count=0; int num=1; String file1="Harry Potter and the Sorcerer's Stone.txt"; try { BufferedReader a=new BufferedReader(new FileReader(file1)); StringBuffer c=new StringBuffer(); String s; while((s = a.readLine()) != null) { c.append(s); } String m=c.toString().toLowerCase(); String [] d=m.split("[^a-zA-Z0-9]+"); Map<String , Integer> myTreeMap=new TreeMap<String, Integer>(); for(int i = 0; i < d.length; i++) { if(myTreeMap.containsKey(d[i])) { count = myTreeMap.get(d[i]); myTreeMap.put(d[i], count + 1); } else { myTreeMap.put(d[i], 1); } } List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(myTreeMap.entrySet()); //按降序排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Entry<String, Integer> k1, Entry<String, Integer> k2) { return k2.getValue().compareTo(k1.getValue()); } }); System.out.println("请输入N的值:"); n=input.nextInt(); for(Map.Entry<String, Integer> map : list) { if(num <= n) { System.out.println(map.getKey() + ":" + map.getValue()); num++; } else break; } a.close(); } catch(FileNotFoundException e) { } catch(IOException e) { } } }