如何读取文件并找到中位数?

时间:2015-10-05 01:19:26

标签: java arrays file

我无法获得打印中位数。谁能告诉我下面的代码有什么问题?

import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;

public class Grades {

    private static Scanner ReadTheseNumbers;

    public static void main (String[] args) throws Exception
    {
        File file = new File( "ReadThis.txt");
        ReadTheseNumbers = new Scanner(file);

        List<Double> grades = new LinkedList<Double>();

        while (ReadTheseNumbers.hasNextInt()) {
            grades.add((double) ReadTheseNumbers.nextInt());
        }
        System.out.println("The average of the numbers in the fe file is: " + avg(grades));
    }

    public static double avg(List<Double> grades) {
        double sum = 0;
        for (Double i : grades) {
            sum += i;
        }
        return (sum / grades.size());
    }

    public static double median (List<Double> grades) {

        Arrays.sort(grades);
        if (grades.length % 2 == 0) {
            return (grades[grades.length/2]+grades[grades.length/2-1])/2.0;
        }
        else {
            return grades[grades.length/2];
        }
        System.out.println("The median is " + median (grades));
    }
    public static int  mode( grades[]) {
        int maxValue, maxCount;

        for (int i = 0; i < grades.length; ++i) {
            int count = 0;
            for (int j = 0; j < grades.length; ++j) {
                if (grades[j] == grades[i]) ++count;
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = grades[i];
            }
        }
        return maxValue;
    }
    System.out.println("The mode is " + mode(numbers));

1 个答案:

答案 0 :(得分:0)

您必须调用median功能,然后打印结果。要关注您的avg示例,

System.out.println("The average of the numbers in the file is: " + avg(grades));

您可以按照上面的内容使用

System.out.println("The median of the numbers in the file is: " 
        + median(grades));

或者,您可以使用格式化的io和

之类的东西
System.out.printf("The average of the numbers in the file is: %.2f%n",
        avg(grades));
System.out.printf("The median of the numbers in the file is: %.2f%n",
        median(grades));

请注意,第二个示例格式为2位精度。

您似乎打算在方法中print。您仍然必须添加电话,

median(grades);
mode(grades);

您可以在main方法中使用Chain-of-responsibility pattern,也可以在median结束时调用avg(最后mode median)。