Counting an Occurrence in an Array (Java)

后端 未结 12 1766
情歌与酒
情歌与酒 2020-12-16 05:23

I am completely stumped. I took a break for a few hours and I can\'t seem to figure this one out. It\'s upsetting!

I know that I need to check the current element in

12条回答
  •  星月不相逢
    2020-12-16 06:17

    @NYB You're almost right but you have to output the count value and also start it from zero on each element check.

        int count=0,currentInt=0;
        for (int i = 0; i < numbers.length; i++)
        {
        currentInt = numbers[i];
        count=0;
    
           for (int j = 0; j < numbers.length; j++)
               {
                 if (currentInt == numbers[j])
                    {
                      count++;
                     }
                }
                System.out.println(count);
          }
    

    @loikkk I tweaked your code a bit for print out of occurrence for each element.

    int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };
    
        Arrays.sort(a);
    
        int nbOccurences = 1;
    
        for (int i = 0, length = a.length; i < length; i++) {
            if (i < length - 1) {
                if (a[i] == a[i + 1]) {
                    nbOccurences++;
                }
            } else {
                System.out.println(a[i] + " occurs " + nbOccurences
                        + " time(s)"); //end of array
            }
    
            if (i < length - 1 && a[i] != a[i + 1]) {
                System.out.println(a[i] + " occurs " + nbOccurences
                        + " time(s)"); //moving to new element in array
                nbOccurences = 1;
            }
    
        }
    

提交回复
热议问题