How can i find the mode in an array? [closed]

偶尔善良 提交于 2019-12-02 13:41:01

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.

Where do you think you are reading 6 integers? You call S.nextInt() only once and don't use its return value. This should be done in your loop to read multiple inputs and do something with them.

You have to ask for every number you want to ask to the user, and if you want the mean you need to use a float or a double.

Scanner S = new Scanner(System.in);
double mean, total;
double input = 6;
double arr1 = new double[input];


for (int i = 0;i<input;++i){
    arr[i] = S.nextDouble();
}

for(int i=0;i<input;i++)
{
 total=total+arr1[i];
}
mean= total/input;

System.out.println("the mean is:" + mean);

Finding the mean is easy; the other answers have covered that.

You also want to make sure you use a loop to gather 6 values for your array, and call nextInt() for all of those values.

The harder part may be the mode. The way I see to solve for the mode is:

1) Sort the array.

2) Create an int to hold the value of your current mode, and another int to hold the number of occurrences of that mode. You'll also need a counter int.

3) Using a loop, run through the sorted array. For every numeric value in the array, count how many times it occurs. Since it's in sorted order, every time the value changes, you know you've counted all of that value. Check to see if the occurrence is larger than the current largest occurrence, and if so, change the occurrence value and the mode value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!