Basic its this program takes input 6 numbers from user, store them in an Array, calculate their Mean and Mode. Also count how many numbers are greater than mean. The code of my program is where i'm wrong
My mean is correct but i have problem in mode.
package p18;
import java.util.Arrays; import java.util.Scanner;
public class P18 {
public static void main(String[] args) {
Scanner S=new Scanner(System.in);
int[] arr1=new int [6];
for (int i = 0; i < 6; ++i) {
int g = S.nextInt();
arr1[i] = g;
}
int input=6;
double total=0d;
double mean;
for(int i=0;i<input;i++)
{
total=total+arr1[i];
}
mean= total/input;
System.out.println("the mean is:" + mean);
PROBLEM STARTS FROM HERE MODE PORTION
int max=0;//problem starts from here
int maxFreq=0;
Arrays.sort(arr1);
max = arr1[arr1.length-1];
int[] count = new int[max + 1];
for (int i = 0; i < arr1.length; i++) {
count[arr1[i]]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > maxFreq) {
maxFreq = count[i];
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] == maxFreq) {
return i;
}}
return -1;
}}
You are not storing the input into the array at all. You need to add something like the following to store the user input:
Scanner S=new Scanner(System.in);
int[] arr1=new int [6];
for (int i = 0; i < 6; ++i) {
int g = S.nextInt();
arr1[i] = g;
}
int input=6;
double total=0d;
double mean;
for(int i=0;i<input;i++)
{
total=total+arr1[i];
}
mean= total/input;
System.out.println("the mean is:" + mean);
I also changed the mean and total to doubles so that you can get a decimal value for the mean, otherwise it would round down.