Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Could anybody help me please to find the mode? Because I don\'t know what\'s wro

ID: 648644 • Letter: C

Question

Could anybody help me please to find the mode? Because I don't know what's wrong with my code the result always be zero :(

Here is the code:

// The mode

   public int getMode()

   {

       int max=0, maxCount=0;

       int array[] = new int[data.length];

       int length=array.length;

      

       for (int i = 0; i <length; ++i) {

      

       int count = 0;

      

       for (int k = 0; k <length; ++k) {

     

       if (array[k] == array[i]) ++count;

      

       }

     

       if (count > maxCount)

     

       {

     

       maxCount = count;

      

       max = array[i];

     

       }

      

       }

      

       return max;

      

       }

Explanation / Answer

public class Mode {
public static int mode(int[] n) {
int max = 0,maxCount = 0;
int[] array = new int[n.length];

for (int i=0; i < n.length; i++) {
array[n[i]]++;
if (maxCount < array[n[i]]) {
maxCount = array[n[i]];
max = n[i];
}
}
return max;
}

public static void main(String[] args) {
int[] n = new int[] { 1,5,7,5,6,7,9,2,4,3,3,5,6,7,5};
System.out.println(mode(n));
}
}