We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the size of the array
int n = scanner.nextInt();
int[] numbers = new int[n];
double sum = 0;
// Read array elements and compute sum for mean
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
sum += numbers[i];
}
// Sort the array for median and mode
Arrays.sort(numbers);
// Calculate mean
double mean = sum / n;
// Calculate median
double median;
if (n % 2 == 0) {
median = (numbers[n / 2 - 1] + numbers[n / 2]) / 2.0;
} else {
median = numbers[n / 2];
}
// Calculate mode
int mode = numbers[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1; i < n; i++) {
if (numbers[i] == numbers[i - 1]) {
currentCount++;
} else {
currentCount = 1;
}
Day 0: Mean, Median, and Mode
You are viewing a single comment's thread. Return to all comments →
import java.util.*;
public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
java code: if (currentCount > maxCount || (currentCount == maxCount && numbers[i] < mode)) { maxCount = currentCount; mode = numbers[i]; } }
}