均值,中位数和模式 - Newb - Java

时间:2015-05-20 05:13:52

标签: java arrays median

我们在Comsci有一个实验室,我无法弄明白。我在这个网站和其他人的帮助下做了很多研究,但他们都是我的头脑。什么让我失望的阵列。无论如何,提前谢谢。我已经获得了成绩,只想知道如何做到这一点:D

PS:我很有意思,我只是找不到偶数编号的中位数,我只是放弃了模式。

import java.util.Arrays;
import java.util.Random;


public class TextLab06st
{

public static void main(String args[])
{
    System.out.println("\nTextLab06\n");
    System.out.print("Enter the quantity of random numbers  ===>>  ");
    int listSize = Expo.enterInt();
    System.out.println();
    Statistics intList = new Statistics(listSize);
    intList.randomize();
    intList.computeMean();
    intList.computeMedian();
    intList.computeMode();
    intList.displayStats();
    System.out.println();
}
}


class Statistics
{

private int list[];         // the actual array of integers
private int size;           // user-entered number of integers in the array
private double mean;        
private double median;      
private int mode;           

public Statistics(int s)
{
    size = s;
    list = new int[size];
    mean = median = mode = 0;
}

public void randomize()
{
    Random rand = new Random(12345);
    for (int k = 0; k < size; k++)
        list[k] = rand.nextInt(31) + 1;  // range of 1..31
}

public void computeMean()
{
    double total=0;
    for (int f = 0; f < size; f++)
    {
        total = total + list[f];
    }
    mean = total / size;

}

public void computeMedian()
{
    int total2 = 0;
    Arrays.sort(list);
    if (size / 2 == 1)
    {
     //   total2 =  
    } 
    else
    {
        total2 = size / 2;
        median = list[total2];
    }



}

public void computeMode()
{
    // precondition: The list array has exactly 1 mode.


}

public void displayStats()
{
    System.out.println(Arrays.toString(list));
    System.out.println();
    System.out.println("Mean:    " + mean);
    System.out.println("Median:  " + median);
    System.out.println("Mode:    " + mode);
}

}

1 个答案:

答案 0 :(得分:1)

以下是mode()public void computeMedian() { Arrays.sort(list); if ( (list.size & 1) == 0 ) { // even: take the average of the two middle elements median = (list[(size/2)-1] + list[(size/2)]) / 2; } else { // odd: take the middle element median = list[size/2]; } } public void computeMode() { // precondition: The list array has exactly 1 mode. Map<Integer, Integer> values = new HashMap<Integer, Integer>(); for (int i=0; i < list.size; ++i) { if (values.get(list[i]) == null) { values.put(list[i], 1); } else { values.put(list[i], values.get(list[i])+1); } } int greatestTotal = 0; // iterate over the Map and find element with greatest occurrence Iterator it = values.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if (pair.getValue() > greatestTotal) { mode = pair.getKey(); greatestTotal = pair.getValue(); } it.remove(); } } 方法的两种实现方式:

{{1}}