2016-03-30 86 views
0

我試圖在我的scores.txt文件中獲得20個數字的均值,但我無法弄清楚如何去做。每次我嘗試,我的輸出都搞砸了。思考?將使用BufferedReader讀取的數字相加

public static void main(String[] args) throws IOException, 
    FileNotFoundException { 

    String file ="/Users/vienna01pd2016/Desktop/scores/src/scores/scores.txt"; 
    processFile("/Users/vienna01pd2016/Desktop/scores/src/scores/scores.txt"); 
    //calls method processFile 
    } 


    public static void processFile (String file) 
    throws IOException, FileNotFoundException{ 
    String line; 
    //lines is declared as a string 


    BufferedReader inputReader = 
     new BufferedReader (new InputStreamReader 
(new FileInputStream(file))); 

    while ((line = inputReader.readLine()) != null){ 

     //System.out.println(line); 
     double Value = Double.parseDouble(line); 
    System.out.println(Value); 
+0

搞砸了什麼意思?你可以發佈程序的輸出和文件輸入 – Harshit

+0

這是我收到的輸出... 0 1 線程「main」中的異常java.lang.RuntimeException:不可編譯的源代碼 - BigInteger(long)具有私有訪問在java.math.BigInteger中 \t在bigintegerfactorial.BigIntegerFactorial.factorial(BigIntegerFactorial.java:38) \t在bigintegerfactorial.BigIntegerFactorial.main(BigIntegerFactorial.java:15) /Users/vienna01pd2016/Library/Caches/NetBeans/8.1/ executor-snippets/run.xml:53:Java返回:1 BUILD FAILED(總時間:10秒 –

+0

這是一個EXCEPTION而不是一個輸出 BigIntegerFactorial.java:38這表明問題出在哪裏,檢查第38行BigIntegerFactorial.java – Harshit

回答

0

如果你有每行一個號碼,我會閱讀使用BufferedReader中的每一行,把它放在一個列表,以及將它添加到一個號碼,那麼你可以通過數字量除以全部在列表中:

package Testers; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.IOException; 
import java.io.FileReader; 
import java.util.ArrayList; 

public class MeanGetter { 

    public static ArrayList<Double> ls = new ArrayList<Double>(); 

    public static void main(String[] args){ 
     String filepath = "/Users/vienna01pd2016/Desktop/scores/src/scores/scores.txt"; 
     double total = processFile(/*new File(filepath).getAbsolutePath()*/ filepath); 
     double mean = total/ls.size(); 
     System.out.println("mean: " + mean); 
    } 

    private static double processFile(String path) { 
     double n = 0; 
     try { 
      BufferedReader reader = new BufferedReader(new FileReader(new File(path))); 
      String line; 
      while ((line = reader.readLine()) != null){ 
       double d = Double.parseDouble(line); 
       n = n + d; 
       ls.add(d); 
      } 
      reader.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return 0; 


    } 

} 
+0

值得一提的是,如果你的應用程序運行在與scores.txt相同的位置,你可以執行'new File(scores.txt).getAbsolutePath();' – JD9999

相關問題