2015-10-05 18 views
0

我無法獲得打印位數。任何人都可以告訴我下面的代碼有什麼問題嗎?如何讀取文件並查找中位數?

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

你的問題不是很容易閱讀。 – hagello

回答

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。您仍然必須通過在avg(和modemedian結束)結束通話median所以你main方法中添加來電,

median(grades); 
mode(grades); 

你可以做,或者用Chain-of-responsibility pattern