package text;
import java.io.File;
import java.util.Scanner;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class zimupinlv {
public static <type> void main (String[] args) throws File {
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
",word,hashMap.get(word));
}
}
}
这个题目中有文件的导入和读取,还有单词个数计算和输出。用了函数hashMap函数,其中的变量Integer是动态的,
不断向后面的单词取值,之后映射给String,从而比较来计数,如果相等就number加1,如果不等就赋值次数为1。