int number=0;
String str = "I'm to go Swimming";//随便输入的字符串
char []ch=str.toCharArray();
Hashtable ht=new Hashtable();
int key=1;
//建立一个Hash表
for(int i=0;i<ch.length;i++)
{
number=0;
boolean is_in=false;//判断当前字母是否存在 

ht.put(key, ch[i]);
key++;
for(int j=1;j<=ht.size();j++)
{
//判断哈希表记录过的字符是否有一样的 
System.out.println("--"+Character.toString(ch[i]));
System.out.println("---"+ht.get(j).toString());
if(Character.toString(ch[i]).equals(ht.get(j).toString()))
{
number++;
is_in=true;
}
if(is_in)
{
ht.put(key, ch[i]);
number=1;
}
}
System.out.println(ch[i]+":"+number);
}怎么都不对!请教各位打个怎么做

解决方案 »

  1.   

    public class Test 

    public static void main(String[] args) 
    { String s = "I'm to go Swimming";StringBuffer buffer = new StringBuffer(s);int pos = 0;
    int sum = 0;
    int tmp;
    char c;while (pos < buffer.length()){
    c = buffer.charAt(pos);
    sum++;
    tmp = pos + 1;
    while (tmp < buffer.length()){
    if (buffer.charAt(tmp) == c){
    sum++;
    buffer.deleteCharAt(tmp);
    }
    else
    tmp++;
    }
    buffer.deleteCharAt(pos);
    System.out.print("Char " + c + " occurs " + sum + "times.");
    System.out.println();
    sum = 0;
    }} 
    }------------ Test Result -------------
    Char I occurs 1times.
    Char ' occurs 1times.
    Char m occurs 3times.
    Char   occurs 3times.
    Char t occurs 1times.
    Char o occurs 2times.
    Char g occurs 2times.
    Char S occurs 1times.
    Char w occurs 1times.
    Char i occurs 2times.
    Char n occurs 1times.
      

  2.   

    基本思路就是:
    1. 先将String存放在一个StringBuffer对象(上面的buffer)里
    2. 从第一个字符开始,遍历整个buffer,一旦发现和它相同的字符,就计数器(sum)加1,并且删除这个字符
      

  3.   

    you can use map machanism instead of stringbuffer for it must have nested loop
    here, i give you some pseudo-code below
    String str = "I'm to go Swimming";//随便输入的字符串 
    char []ch=str.toCharArray(); 
    new a Hashmap//the character is as key, the times as value
    for(Char c: ch){
    judge whether the map contains value if yes then get whose value and increasing one time
    else put the one time value into which
    }
    hope that can help you
      

  4.   

    ls说很全面hashmap key存字符value存次数
      

  5.   

    直接用String里的toCharAarray()方法先转成个字符数组
    然后用HashMap做个小统计就OK
    代码不超过10行晕,就是LS的LS的
      

  6.   

    按照LS们的思想,来一个具体实现import java.util.HashMap;
    import java.util.Map;public class Satistic {
    public static void main(String args[]){
    String s="I'm to go Swimming";
    char []ch=s.toCharArray();
    Map<Character,Ctime> map=new HashMap<Character, Ctime>();
    for(char c:ch){
    if(map.containsKey(c))
    ((Ctime)map.get(c)).count++;
    else
    map.put(c,new Ctime());
    }
    System.out.println(map);
    }
    }
    class Ctime{
        int count=1;
        public String toString(){
             return Integer.toString(count);
        }
    }
      

  7.   


    原来Java类还可以像Ctime这样用,茅塞顿开啊~
    以前做项目需要进行计数统计的时候知道这个用法就好了。
    受教了!