我试图在我的scores.txt文件中获得20个数字的平均值,但我无法弄清楚如何做到这一点。每次我尝试,我的输出都搞砸了。想法?
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 :(得分: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;
}
}