-3
    int[] nilai = {12,10,8,6,12,12,34,10,8,6,9,9,34,12,6,8,10,34,12,10,9,12};

    int[] frekuensi = new int[23];


    for (int i=0; i<nilai.length; i++) {
        frekuensi[i] = 0;
    }

    for (int i=0; i<nilai.length; i++) {
        frekuensi[nilai[i]]++;
    }

    int modus = 0;
    for (int i=0; i<nilai.length; i++) {
        if (frekuensi[i] > modus) {
            modus = i;
        }
    }        
    System.out.println("Nilai Modusnya = " + modus);
AntonH
  • 6,359
  • 2
  • 30
  • 40

2 Answers2

1

There are several approaches to your problem:

  1. Sort the array and count which is the number with more appearances
  2. Use a map and count appearances for each distinct number (then, by iterating the map, you will easily find the most frequent one).
  3. Use multiple loops (apparently this is what you are trying to do) to compute what's the most frequent number.
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
0

Using Java 8 it is one-liner (not so readable). Explained in comments:

    int[] nilai = { 12, 10, 8, 6, 12, 12, 34, 10, 8, 6, 9, 9, 34, 12, 6, 8, 10, 34, 12, 10, 9, 12 };
    Integer maxKey = IntStream.of(nilai).boxed() // create an Stream from the int array
            .collect(Collectors.groupingBy(i -> i, Collectors.counting())) // count the occurrences of every number and convert it to map of (number, occurences)
            .entrySet().stream() // convert the map entries into stream
            .max((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // obtain the map entry with largest occurrences count
            .map(Map.Entry::getKey).get(); // obtain the number that occurred the most often
    System.out.println(maxKey);
Pawel P
  • 131
  • 5