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);
Asked
Active
Viewed 171 times
-3

AntonH
- 6,359
- 2
- 30
- 40
-
2What? You're going to have to explain your problem a lot better than this. – Carcigenicate May 08 '17 at 13:57
-
1You're going to have to define "often" in this context. Appear more than average? Appear more than a given value? Appear more that its own value? Other...? – AntonH May 08 '17 at 13:58
-
2Possible duplicate of [Find the most popular element in int\[\] array](http://stackoverflow.com/questions/8545590/find-the-most-popular-element-in-int-array) – Ousmane D. May 08 '17 at 14:01
-
Values that often appear from the array above, the answer is 12 because appear in 6 times @AntonH – Rizky Ade Pratama Putra May 08 '17 at 14:22
-
@RizkyAdePratamaPutra Do you maybe mean "the most often"? – AntonH May 08 '17 at 14:23
-
yes, i'm sorry for bad language @AntonH – Rizky Ade Pratama Putra May 08 '17 at 14:28
2 Answers
1
There are several approaches to your problem:
- Sort the array and count which is the number with more appearances
- Use a map and count appearances for each distinct number (then, by iterating the map, you will easily find the most frequent one).
- 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