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 Program to Represent Linear Equations in Matrix Form
Spring Boot - Rest Template
Set Interface trong Java
Java Program to subtract two large numbers using Linked Lists
Spring Boot - Securing Web Applications
Introduction to Spring Cloud Stream
Java Program to Implement Range Tree
Limiting Query Results with JPA and Spring Data JPA
DistinctBy in the Java Stream API
Deploy a Spring Boot App to Azure
Circular Dependencies in Spring
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Functional Interfaces in Java 8
Prevent Cross-Site Scripting (XSS) in a Spring Application
Removing all Nulls from a List in Java
Redirect to Different Pages after Login with Spring Security
Java 8 – Powerful Comparison with Lambdas
Spring Boot - Web Socket
Fixing 401s with CORS Preflights and Spring Security
Giới thiệu Google Guice – Injection, Scope
Hướng dẫn Java Design Pattern – Iterator
Java Program to Implement Counting Sort
How to Store Duplicate Keys in a Map in Java?
Spring Boot - Cloud Configuration Client
Java Program to Implement Stack using Two Queues
Java Program to Find Transpose of a Graph Matrix
Introduction to Java 8 Streams
Java Program to Implement Adjacency Matrix
Spring – Injecting Collections
Introduction to the Java NIO2 File API
Merging Two Maps with Java 8
Java Program to Find a Good Feedback Edge Set in a Graph