关于if else后面加不加大括号的区别,加括号会执行里面的全部语句,不加只执行第一条语句,受教了。比对了一下午才弄明白问题所在。
- import java.util.*;
- class MapTest3
- {
- public static void main(String[] args)
- {
- String s = charCount("abaassbswwbweeberrbrtbtt");
- System.out.println(s);
- }
- public static String charCount(String str)
- {
- char[] chs = str.toCharArray();
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
- for (int x= 0; x<chs.length; x++)
- {
- Integer value = tm.get(chs[x]);
-
- if(value == null)
- {
- tm.put(chs[x],1);
- }
- else
- //跟着老毕的视频试着自己敲代码,else这里没加大括号一直显示字母出现次数是null,原来是else没加大括号,只执行了第一句。
- {
- value = value+1;
- tm.put(chs[x],value);
- }
- }
- StringBuilder sb = new StringBuilder();
- Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
- while (it.hasNext())
- {
- Map.Entry<Character,Integer> me = it.next();
- Character ch = me.getKey();
- Integer v = me.getValue();
- sb.append(ch+"("+v+")");
- }
- return sb.toString();
- }
- }
复制代码 |
|