我正在用Java编写一个程序,它遍历文本文件的每一行,这个文本文件包含单独行的数字,我已成功地让程序读取每一行并将它们打印到一个新文件。
但是我试图将这些数字的平均值打印到新文件中,我知道我必须将每一行视为浮点数或双精度(因为我使用的是十进制数)但我是不确定如何做到这一点,这是我到目前为止所做的。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Run {
public static void main(String[] args) throws Exception {
Write(); //call Write method
}
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
//int mynewLine = Integer.parseInt(lineCut);
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}
答案 0 :(得分:0)
基本上这就是你正在做的事情
因此,在上述每个操作中,您从未将该行视为Number
。要查找平均值,您需要将每行数分析为实数Number
,Double.parseDouble("21.2")
等,并在每次迭代中,您知道该怎么做:-)
例如:
double sum= 0;
int count = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
int num = Double.parseDouble(lineCut);
sum = sum + num; count++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
br.write(String.valueOf(sum/count));
答案 1 :(得分:-1)
未经测试。我正在考虑每一行都有一个数字,没有别的。请记住,您应检查linecount上的valou以避免在从String转换为float期间出现异常。
#define NORETURN __attribute__((noreturn))