2015-02-06 26 views
-1

我在寫一個名爲fileAverage的公共靜態方法,它接受一個字符串,它是文件的絕對路徑。該文件是一個帶有實數的簡單文本文件。我需要用try catch來處理文件。我的catch塊應該打印出有關異常的信息,我的方法不應該拋出異常。我的方法,他們應該返回一個文件的平均值的雙。java方法讀取文件並返回avg

這是到目前爲止我的代碼:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.util.logging.Level; 
import java.util.logging.Logger; 


public class Problem2 { 

    public static final String filePath = "/Users/rderickson9/Desktop/CS2/fileAverage.txt"; 

    public static double fileAverage(String filePath){ 
     int total = 0; 
     double fin = 0.0; 
     double avg = 0; 

     File file = new File(filePath); 
     try { 
      Scanner sc = new Scanner(file); 
      while(true){ 
       String nextLine = sc.nextLine(); 
       if(nextLine.equals("")){ 
        break; 
       } 
       double doubleTemp = Double.parseDouble(nextLine); 
       fin = fin + doubleTemp; 

       total++; 
      } 
      avg = (fin/total); 
      System.out.println(avg); 
     } catch (FileNotFoundException ex) { 
      Logger.getLogger(Problem2.class.getName()).log(Level.SEVERE, null, ex); 
     } 


     return avg; 
    } 
    public static void main(String[] args) { 
     fileAverage(filePath); 

    } 
} 

我真的不下面如何設置此所以我的方法將運行文件的

例如

3.2 
4.7 
2003 
2.3 
25 
+0

如果你的Java 7或8,可以考慮使用'嘗試(掃描儀SC =新的掃描儀(文件)){...}'有文件在關閉結束。 – Cfx 2015-02-06 18:55:51

+0

那麼...什麼不工作? – 2015-02-06 19:22:29

回答

1

你可以直接從文件中使用Scanner class這樣取出雙倍

while (sc.hasNextLine()) { 
double doubleTemp = sc.nextDouble(); 
fin += doubleTemp; //short hand operator 
    total++; 
} 
avg = (fin/total); 
System.out.println(avg); 
0

這裏是一個Java 8的解決方案:

List<String> l = new LinkedList<>(); 
try (Scanner sc = new Scanner(file)) { 
    sc.useDelimiter("\\v").forEachRemaining(l::add);   
    l.stream().mapToInt(Integer::parseInt).average().ifPresent(System.out::println); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
}