lundi 30 novembre 2020

Method for returning the mode that occurs most frequently

I need help on this problem:

Write the method mode that accepts an array of test grades(0 – 100) and return the mode, the grade that occurs most frequently. If there are multiple modes, return the smallest.

My code does not work: Please help, thanks!

public static int mode(int[] marks) {
    int count = 0;
    int count0 = 0;
    int mostFrequent = marks[0];
    for (int x = 0; x < marks.length; x++) {
        if (marks[x] == mostFrequent) {
            count++;
        }
    }
    if (count>count0) {
       count0  = count;
       mostFrequent = marks[count];
    }
    return mostFrequent;
}

E.g:

If marks = {1,2,4,6,1,1,1}, it works

if marks = {1,2,4,1,3,2,3,5,5}, it does not work

Aucun commentaire:

Enregistrer un commentaire