我无法获得打印中位数。谁能告诉我下面的代码有什么问题?
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));
答案 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
)。