【问题标题】:How to count occurance of element in array? [duplicate]如何计算数组中元素的出现次数? [复制]
【发布时间】:2014-09-30 19:36:52
【问题描述】:

我写了一个类,如下所示

 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

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

【问题讨论】:

  • 任何人都可以提供示例编码吗?因为我尝试了很多方法但我无法解决它请帮助

标签: java arrays loops for-loop logic


【解决方案1】:

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

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】:

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

    cmets 中链接的答案使用Map,但如果您出于某种原因不想使用它,还有其他一些方法。在 map 之后我的第一个想法是一个字符计数数组。

    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
    }
    

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

    【讨论】:

      【解决方案3】:

      您应该使用 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】:

        这里的问题是您的逻辑会找到已计数的字母数。它不显示 d 的计数,因为您创建了一个检查 i 的循环。该字符串是一个 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);
          }
          }
        }
        

        【讨论】:

          【解决方案5】:

          这是一个逻辑错误。

          您正在取第一个字母并检查它在字符串中再次出现的次数,然后取第二个字符来计算它再次出现的次数。

          同样的,您要使用每个字符,而不是如果一个字符第二次或第三次出现,或者您应该跳过该字符。

          下面的代码会对你有所帮助。

          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;
          }
          

          }

          【讨论】:

            【解决方案6】:

            虽然我强烈建议您使用上面建议的 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);
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2022-11-30
              • 2015-08-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多