本帖最后由 李知伦 于 2012-8-20 18:07 编辑
Line31不应该用while,应该用if, 因为判断条件user.indexOf(zimu)在循环体内没有改变,一直是-1,也就出现了死循环
Line29改变了user的值, 下一轮循环(x=1), 导致Line25的user取值就不对了
我用HashMap写的- import java.util.HashMap;
- import java.util.Map;
- public class getCharTimes {
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str = "sdfasdewefqmcoad";
- String character = "";
- int frequency = 0;
- Map<String, Integer> map = new HashMap<String, Integer>();
- for (int i=0; i < str.length(); i++) {
- String key = str.substring(i, i+1);
- if (map.containsKey(key)) {
- map.put(key, map.get(key)+1);
- }
- else {
- map.put(key, 1);
- }
- }
- for (Map.Entry<String, Integer> m : map.entrySet()) {
- //取得最终的Key,value
- character = m.getKey();
- frequency = m.getValue();
- System.out.println(character + "(" + frequency + ")");
- }
- }
- }
复制代码 |