- this is a cat and that is a mice and where is the food?
- 統(tǒng)計(jì)每個(gè)單詞出現(xiàn)的次數(shù)
- 存儲(chǔ)到map中,因?yàn)閙ap里每個(gè)key只能出現(xiàn)一次
- String=key;
- value為自定義類型
- “分”揀思路
- 1.為所有key創(chuàng)建容器
- 第二次才把對(duì)應(yīng)的value存放進(jìn)去
- 2.第一次創(chuàng)建容器,并且把value存放進(jìn)去
- 第二次之后,直接使用容器,存放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 方法就省略了,這個(gè)里面,只用到了count來存放字符出現(xiàn)的次數(shù)
- 這個(gè)類里面一開始我用Integer來定義count,然后空構(gòu)造器會(huì)自動(dòng)把Integer賦值為null;此時(shí)我下面程序里面的count+1就會(huì)出錯(cuò),因?yàn)閏ount+1的過程,自己先得拆分,調(diào)用的是count.intValue();但是count為null此時(shí)調(diào)用方法會(huì)提示空指針錯(cuò)誤了!!
- 而int則會(huì)默認(rèn)賦值為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(" ");
//存儲(chǔ)到map中
Map<String, Letter> letters=new HashMap<String, Letter>();
for(String temp:strs){
//為每一個(gè)key創(chuàng)建一個(gè)容器,似乎把Letter當(dāng)做存放的容器了
if(!letters.containsKey(temp)){
letters.put(temp, new Letter());
}
}
for(String temp:strs){
Letter col=letters.get(temp);//獲取上面創(chuàng)建的容器,因?yàn)閗ey是字符串,所以,每個(gè)字符串對(duì)應(yīng)一個(gè)容器
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){
//為每一個(gè)key創(chuàng)建一個(gè)容器,然后把value放進(jìn)去
if(null==(col=letters.get(temp))){//沒有就建
//Letter col=new Letter();
col=new Letter();
col.setCount(1); //放進(jìn)去,即數(shù)目加1
letters.put(temp,col);
}else{
col.setCount(col.getCount()+1); //放進(jìn)去,即數(shù)目加1
}