- this is a cat and that is a mice and where is the food?
- 統(tǒng)計每個單詞出現(xiàn)的次數(shù)
- 存儲到map中,因為map里每個key只能出現(xiàn)一次
- String=key;
- value為自定義類型
- “分”揀思路
- 1.為所有key創(chuàng)建容器
- 第二次才把對應(yīng)的value存放進去
- 2.第一次創(chuàng)建容器,并且把value存放進去
- 第二次之后,直接使用容器,存放value
自定義類
public class Letter {
private String name;
private int count;
public Letter(String name, int count) {
super();
this.name = name;
this.count = count;
}
public Letter() {
}
get set 方法就省略了,這個里面,只用到了count來存放字符出現(xiàn)的次數(shù)
- 這個類里面一開始我用Integer來定義count,然后空構(gòu)造器會自動把Integer賦值為null;此時我下面程序里面的count+1就會出錯,因為count+1的過程,自己先得拆分,調(diào)用的是count.intValue();但是count為null此時調(diào)用方法會提示空指針錯誤了!!
- 而int則會默認賦值為0,如果要用Integer的話,在空構(gòu)造器里頭就得給他賦值為0啦。
思路一
public static void main(String[] args) {
//放到字符串里面
String string=new String("this is a cat and that is a mice and where is the food");
//以空格區(qū)分,將string分開
String[] strs=string.split(" ");
//存儲到map中
Map<String, Letter> letters=new HashMap<String, Letter>();
for(String temp:strs){
//為每一個key創(chuàng)建一個容器,似乎把Letter當做存放的容器了
if(!letters.containsKey(temp)){
letters.put(temp, new Letter());
}
}
for(String temp:strs){
Letter col=letters.get(temp);//獲取上面創(chuàng)建的容器,因為key是字符串,所以,每個字符串對應(yīng)一個容器
col.setCount(col.getCount()+1);//如果碰見一次一樣的就加一
}
//輸出map的值
Set<String> keys=letters.keySet();
for(String temp:keys){
Letter col=letters.get(temp);
Integer i=col.getCount();
System.out.println("單詞"+temp+"出現(xiàn)次數(shù):"+i);
}
}
}
思路二
Letter col=null; //簡化程序
for(String temp:strs){
//為每一個key創(chuàng)建一個容器,然后把value放進去
if(null==(col=letters.get(temp))){//沒有就建
//Letter col=new Letter();
col=new Letter();
col.setCount(1); //放進去,即數(shù)目加1
letters.put(temp,col);
}else{
col.setCount(col.getCount()+1); //放進去,即數(shù)目加1
}