给大家推荐个靠谱的公众号程序员探索之路,大家一起加油
import java.io.*;
import java.util.*;
public class SearchWordTimes {
/**先调用 读取文件方法 然后 记录 方法 然后 打印方法
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file =new File("file/qfile.txt");
HashMap<String,Integer> map = new HashMap<String,Integer>();
Set<String> set = new HashSet<String>();
String[] str = read(file).split(" ");
record(map,set,str);
print(map);
}
/**
* 将 file路径下的文件读出来
* @param file
* @return 返回读出来的文件内容的字符串形式
* @throws IOException
*/
public static String read(File file) throws IOException{
BufferedReader read = new BufferedReader(new FileReader(file));
StringBuffer str = new StringBuffer();
String s = null;
while((s = read.readLine()) != null){
str.append(s);
}
return str.toString();
}
/**
* 将传进来的字符串数组 检测处每个单词出现了多少次 map的键是单词 值是次数
* 注意:由于开头字母大写 与不大写的单词 是同一个单词 那么 都转换为小写的处理
* 如果 单词 能够 存进 set集合中 那么就是 一个 新的单词 出现的次数就是 1 如果不能说明 是出现过的单词
* 那么就把 对应的值取出来 删除带健值对 次数加1 重新存入
* 特殊单词 就是 后面加's的单词 这是 两个单词 需要 单独处理
* @param map
* @param set
* @param str
*/
public static void record(HashMap map,Set set,String[] str){
for(int i = 0;i < str.length;i++){
str[i] = change(str[i]);
//单独处理
if(str[i].length() > 1&&Character.toString(str[i].charAt(str[i].length() - 2)).equals("'")){
str[i] = str[i].substring(0,str[i].length() - 2);
if(set.add("is")){
map.put("is", 1);
}else{
int num =(Integer)map.get("is") + 1;
map.remove("is");
map.put("is", num);
//System.out.println("is = " + num);
}
}
if(set.add(str[i])){
map.put(str[i], 1);
//System.out.println(str[i] + 1);
}else{
int num =(Integer)map.get(str[i]) + 1;
map.remove(str[i]);
map.put(str[i], num);
//System.out.println(str[i] + " = " + num);
}
}
}
/**
* 检测str第一个字母是否大写如果是 那么把大写转换为小写
* @param str
*/
public static String change(String str){
char ch = str.charAt(0);
if(ch >= 'A'&&ch <= 'Z'){
return str.replace(Character.toString(ch), Character.toString((char)(ch + 32)));
}
return str;
}
/*
* 输入单词 打印出现的次数
*/
public static void print(HashMap map){
Scanner s = new Scanner(System.in);
String str = s.next();
str = change(str);
if(map.get(str) == null){
System.out.println("您输入单词不在文章中");
}else{
System.out.println(map.get(str));
}
}
}