编程实现统计文本文件中某个单词的出现频率,并输出统计结果

用HashMap来解决
假设单词不存在跨行的,每个单词用,. ;分割    

import java.io.*;
import java.util.*;

public class FindWord {
	public void countNum()throws IOException{
		BufferedReader br=null;
try{
	br= new BufferedReader(new FileReader("D://111.txt"));
			Map map= new HashMap();
for(String s=br.readLine(); s!=null; s=br.readLine()){
	StringTokenizer st= new StringTokenizer(s,",. ;");
	while(st.hasMoreTokens()){
		String temp=st.nextToken();
		if(map.containsKey(temp)){
	map.put(temp, new Integer((Integer)map.get(temp)+1));
					}else{
		map.put(temp, new Integer(1));
					}
					
				}
			}
for(Iterator it=map.entrySet().iterator();it.hasNext();){
Map.Entry entry=(Map.Entry)it. next();        
System.out.println(entry.getKey()+"-->"+entry.getValue());
			}
		}catch(Exception e){
			e.printStackTrace();	
		}finally{
			br.close();		
		}		
	}
public static void main(String[] args)throws IOException{
	FindWord fw=new FindWord();
	fw.countNum();
	}

}

 

你可能感兴趣的:(java面试)