This is a java program to find the mode of a set. The mode of a set is defined as the highest occurring element in the set. We count the occurrence of each of the element and print the element whose count is highest.
Here is the source code of the Java Program to Find the Mode in a Data Set. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a java program to find the mode for a given sequence of numbers
import java.util.Random;
public class Mode
{
static int N = 20;
static int[] sequence = new int[N];
public static int mode()
{
int maxValue = 0, maxCount = 0;
for (int i = 0; i < sequence.length; ++i)
{
int count = 0;
for (int j = 0; j < sequence.length; ++j)
{
if (sequence[j] == sequence[i])
++count;
}
if (count > maxCount)
{
maxCount = count;
maxValue = sequence[i];
}
}
return maxValue;
}
public static void main(String args[])
{
Random random = new Random();
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("The set of numbers are: ");
for (int i = 0; i < N; i++)
System.out.print(sequence[i] + " ");
System.out.println("\nThe mode of the set is: " + mode());
}
}
Output:
$ javac Mode.java $ java Mode The set of numbers are: 85 3 80 56 37 47 13 11 94 38 6 12 10 31 52 67 81 98 43 37 The mode of the set is: 37
Related posts:
Java Scanner hasNext() vs. hasNextLine()
Serialization và Deserialization trong java
Java List UnsupportedOperationException
Mệnh đề Switch-case trong java
Java Program to Implement Knapsack Algorithm
Java Program to Find Nearest Neighbor for Static Data Set
StringBuilder vs StringBuffer in Java
Spring Security Basic Authentication
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Luồng Daemon (Daemon Thread) trong Java
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Hướng dẫn Java Design Pattern – Mediator
Java Program to Implement Patricia Trie
Apache Commons Collections OrderedMap
Automatic Property Expansion with Spring Boot
A Guide to EnumMap
Java Program to Implement Interpolation Search Algorithm
Tránh lỗi NullPointerException trong Java như thế nào?
HttpAsyncClient Tutorial
The DAO with Spring and Hibernate
Java Collections Interview Questions
A Guide to JUnit 5 Extensions
Java Program to Solve Knapsack Problem Using Dynamic Programming
Cachable Static Assets with Spring MVC
Java Program to Perform Uniform Binary Search
New Features in Java 9
Java Program to Implement Hopcroft Algorithm
Configure a Spring Boot Web Application
Vòng lặp for, while, do-while trong Java
Java Program to Implement Sorted Singly Linked List
Java Program to Implement DelayQueue API
A Guide to Java HashMap