rajpoot rana rajpoot rana - 5 months ago 13
Java Question

How can i find the mode in an array?

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

package p17;
import java.util.Scanner;
/**
*
* @author WAQAR
*/
public class P17 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner S=new Scanner(System.in);
int[] arr1=new int [6];
int g=S.nextInt();
int input=6;
int total=0;
int mean;
for(int i=0;i<input;i++)
{
total=total+arr1[i];
}
mean= total/input;
System.out.println("the mean is:" + mean);
}
}

Answer

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.