Number of queries word appears in a document

package text;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class zimupinlv {
    public static <type> void main (String[] args) throws FileNotFoundException {
        File file=new File("C:\\Users\\冯静妃\\Desktop\\StringBuffer.txt");
        if(!file.exists()){
            System.out.println("文件不存在");
            return;
        }  
        Scanner scanner=new Scanner(file);
        HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
        while(scanner.hasNextLine()) {
            String line=scanner.nextLine();
            String[] lineWords=line.split("\\W+");
            Set<String> wordSet=hashMap.keySet();
            for(int i=0;i<lineWords.length;i++) {
                if(wordSet.contains(lineWords[i])) {
                    Integer number=hashMap.get(lineWords[i]);
                    number++;
                    hashMap.put(lineWords[i], number);
                }
                else {
                    hashMap.put(lineWords[i], 1);
                }
            }
        }
        Iterator<String> iterator=hashMap.keySet().iterator();
        while(iterator.hasNext()) {
            String word=iterator.next();
            System.out.printf("单词:%-12s 出现次数:%d\n",word,hashMap.get(word));
        }
        }      This problem has file into and reading, as well as the number of words is calculated and output. HashMap function with the function, wherein Integer variables are dynamic, continuously to the value after the word, then mapped to String, to compare counts, if the number equal to plus 1, if the number of times ranging from 1 to assignment.
}


 

Guess you like

Origin www.cnblogs.com/fengjingfei/p/11595141.html