一.先贴出自己的代码
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 import java.io.IOException; 5 import java.util.Arrays; 6 import java.util.HashMap; 7 import java.util.Iterator; 8 import java.util.Map; 9 import java.util.Map.Entry; 10 public class Search { 11 public void ReadBook()throws Exception 12 { 13 String book=book("D:/book.txt"); 14 System.out.println(book); 15 } 16 17 private static String book(String file) throws IOException 18 { 19 // TODO Auto-generated method stub 20 File f=new File(file); 21 BufferedReader bf=new BufferedReader(new FileReader(f)); 22 String content=""; 23 int lenth=0; 24 int x=0; 25 StringBuilder sb=new StringBuilder(); 26 String[] sum= {""}; 27 while(content!=null) 28 { 29 30 content= bf.readLine(); 31 if(content==null) 32 break; 33 34 content=content.replace(",",""); 35 content=content.replace(".",""); 36 content=content.replace(";",""); 37 content=content.replace("(",""); 38 content=content.replace(")",""); 39 String[] temp = content.split(" "); 40 41 int length1=temp.length; 42 43 int length2=sum.length; 44 sum = Arrays.copyOf(sum, length2 + length1);// 扩容 45 // System.out.println("???"); 46 x=0; 47 for(lenth=length2;lenth<(length1+length2);lenth++) 48 { 49 50 sum[lenth]=temp[x]; 51 x++; 52 } 53 // for(int xx=0;xx<sum.length;xx++) 54 // { 55 // System.out.println(sum[xx]); 56 // } 57 Map<String,Integer> map=new HashMap<String,Integer>(); 58 for(String str : sum){ 59 if(map.containsKey(str)){ 60 map.put(str, map.get(str) + 1); 61 }else{ 62 map.put(str, 1); 63 } 64 } 65 Iterator<Entry<String, Integer>> it = map.entrySet().iterator(); 66 while(it.hasNext()){ 67 Entry ex = (Entry) it.next(); 68 System.out.println(ex.getKey() + ":" + ex.getValue()); 69 70 } 71 72 73 74 75 } 76 bf.close(); 77 return sb.toString(); 78 } 79 }
1 public class main { 2 3 public static void main(String[] args) throws Exception { 4 // TODO Auto-generated method stub 5 Search s=new Search(); 6 s.ReadBook(); 7 8 9 10 } 11 12 }
二.思路
1.当时看到实验题目第一反应就是要读文件,然后也没有多想,就去先搞文件
2.文件搞完了,就去想想要去吧符号去掉,然后在把所有的单词整合到一起
3.最后就是用方法进行统计