均值、中值和众数 - Newb - Java

Mean, Median, and Mode - Newb - Java

我们在 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);
}

}

下面是 median()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();
    }
}