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:
Hướng dẫn Java Design Pattern – Facade
Reversing a Linked List in Java
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Guide to the Synchronized Keyword in Java
A Guide to System.exit()
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Implement Regular Falsi Algorithm
Hướng dẫn Java Design Pattern – DAO
Spring Boot - Servlet Filter
Spring Boot - Rest Controller Unit Test
Supplier trong Java 8
Java Program to Generate Random Numbers Using Multiply with Carry Method
A Guide To UDP In Java
JWT – Token-based Authentication trong Jersey 2.x
Hướng dẫn sử dụng Printing Service trong Java
Guide to Escaping Characters in Java RegExps
The StackOverflowError in Java
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Implement Stack
Java Program to Implement Binomial Heap
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Java Program to Implement Johnson’s Algorithm
Creating Docker Images with Spring Boot
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Java InputStream to String
Check If a File or Directory Exists in Java
Java Program to Implement Selection Sort
Java Program to Implement PriorityBlockingQueue API
A Guide to Spring Boot Admin
Java Program to do a Depth First Search/Traversal on a graph non-recursively