如何计算数组中元素的出现?

时间:2014-08-07 14:02:58

标签: java arrays loops for-loop logic

我写了一个类,如下所示,

 public class Countletter 
 {
    public static void main(String args[]) throws IOException
    {        
      String str = "muhammed"; 
      char[] Array = str.toCharArray();

     for(int i=0;i<8;i++)
     {
       int count=1;
       for(int j=i+1;j<8;j++)
       {
        if(Array[i]==(Array[j]))
        {
            count++;
        }
       }
    System.out.println(""+Array[i]+":"+count);
    }
  }
}

输出应为,

Input  : Muhammed

output : m=3
         u=1
         h=1
         a=1
         d=1

但我的代码打印如

    output :  m:3
              u:1
              h:1
              a:1
              m:2
              m:1
              e:1
              d:1

有谁知道我的错在哪里?如果有人知道这个逻辑,请帮帮我

6 个答案:

答案 0 :(得分:1)

基本上你的代码正在计算从那一点开始的每个字母的频率,因为你的循环并不关心字母是否已计算在内。

评论中链接的答案使用Map,但如果您因某些原因不想使用该答案,则还有一些其他方法。我在地图之后的第一个想法是char count数组。

int counts = new int[26];                 //Only counting lowercase letters
for(int i=0; i<counts.size(); i++)
    counts[i] = 0;                        //initialize all to 0
int a = 'a';                              //get the int representation of the first lowercase letter
str = str.toLowerCase();
for(int i = 0; i<str.length; i++){
    int let = ((int)str.charAt(i))-a;     //find the appropriate index in the count
    counts[let]++;                        //increment that letters count
}
for(int i =0; i<counts.size(); i++){
    if(c > 0)
        print(char(i+a) + ": " + c);      //only print the letters that exist
}

这会产生你想要的输出,尽管按字母顺序排列。

答案 1 :(得分:1)

错误是循环不跳过已经计数的项目,例如对于外部循环执行的时间

i=0 and gives count 3 for positions 0,4,5
 i=4 and gives count 2 for positions 4,5
 i=5 and gives count 1 for position 5

要防止再次复制它们,您可以用空格或任何特殊字符替换它们,如下所示。

public class Countletter 
 {
    public static void main(String args[]) throws IOException
    {        
      String str = "muhammed"; 
      char[] Array = str.toCharArray();

     for(int i=0;i<8;i++)
     {
         if(Array[i]!=' '){
          int count=1;
           for(int j=i+1;j<8;j++)
           {
            if(Array[i]==(Array[j]))
            {
             count++;
             Array[j]=' ';
            }
          }
        System.out.println(""+Array[i]+":"+count);
       }
    }
  }
}

答案 2 :(得分:0)

这里的问题是你的逻辑找到已经计数的字母数。它创建了一个检查 i&lt; 7 即可。该字符串是一个8个字符的字符串。

import java.io.IOException;

public class Countletter 
{
public static void main(String args[]) throws IOException
{        
  int flag = 0;
  String str = "muhammed"; 
  char[] Array = str.toCharArray();

 for(int i=0;i<8;i++)
 {
     flag = 0;

   for (int k = 0 ; k < i ; k++)
   {
       if (Array[k] == Array[i])
           {
           flag = 1;
           break;
           }
   }
   int count=1;

   for(int j=i+1;j<8;j++)
   {
    if(Array[i]==(Array[j]))
    {
        count++;
    }
   }
   if (flag != 1)
       System.out.println(""+Array[i]+":"+count);
  }
  }
}

答案 3 :(得分:0)

您应该使用LinkedHashMap来计算字符数。 LinkedHashMap保持字符出现的顺序。

    String str = "muhammed"; 
    char[] array = str.toCharArray();
    Map<Character, Integer> countMap = new LinkedHashMap<Character, Integer>();
    for(char c:array) {
        Integer cnt = countMap.containsKey(c) ? countMap.get(c) + 1 : 1;
        countMap.put(c, cnt);
    }
    for(Map.Entry<Character, Integer> entry: countMap.entrySet()) {
        System.out.println("" + entry.getKey() + ": " + entry.getValue());
    }

输出:

m: 3
u: 1
h: 1
a: 1
e: 1
d: 1

答案 4 :(得分:0)

这是一个合乎逻辑的错误。

您正在收取第一个字母并检查字符串中再次发生的时间,然后计算第二个字符,计算它再次发生的时间。

相同的是你正在拍摄每一个角色,相反,如果一个角色第二次或第三次出现,或者你应该跳过角色。

以下代码可以为您提供帮助。

public class Countletter {
public static void main(String args[]) throws IOException {
    String str = "aaaabbbbabab";
    char[] Array = str.toCharArray();

    for (int i = 0; i < str.length(); i++) {
        int count = 1;
        boolean charCameAlready=check(Array,Array[i],i);
        if(charCameAlready==false){
            for (int j = i + 1; j < str.length(); j++) {
                if (Array[i] == (Array[j])) {
                    count++;
                }
            }
            System.out.println("" + Array[i] + ":" + count);
        }
    }
}

private static boolean check(char[] array, char c,int limit) {
    for(int i=0;i<limit;i++){
        if(array[i]==c){
            return true;
        }
    }
    return false;
}

}

答案 5 :(得分:0)

虽然我强烈建议您按照上面的建议使用Map对象,但您可以在代码中更改以使其正常工作:

String str = "muhammed";
char[] Array = str.toCharArray();

List<String> countedLetters = new ArrayList<String>();

for (int i = 0; i < 8; i++) {
    int count = 1;
    if (!countedLetters.contains("" + Array[i])) {
        for (int j = i + 1; j < 8; j++) {
            if (Array[i] == Array[j]) {
                count++;
            }
        }
        countedLetters.add("" + Array[i]);
        System.out.println("" + Array[i] + ":" + count);
    }
}