我想读取一个包含两列 float 的文件。然后我想打印每列的平均值。
有 2 列有数字 - 换句话说,每行有 2 个数字。这是一个例子:
文件包含:
7 3
5 2
9月11日
10 12
输出应该是:
第 1 列的平均值为 7,75
第 2 列的平均值为 7
到目前为止我有这个代码:
public class MainApp {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "columns.txt";
double number = 0;
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextLine()) {
number = number + Integer.parseInt(scanner.next());
number = number / 2;
System.out.println(number);
}
}
scanner.close();
}
}
最佳答案
如果您期望双倍输出,那么最好将数字解析为 double,而不是 int。
您可以使用String.split
在空格上分割行,然后解析 double :
double first = 0.0;
double second= 0.0;
int lines = 0;
if (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] numbers = line.split("\\s+"); // split on white spaces
first += Double.parseDouble(numbers[0]);
second += Double.parseDouble(numbers[1]);
lines++;
}
if (lines > 0) {
System.out.println(first / lines);
System.out.println(second / lines);
}
关于java - 如何读取包含两列数字的文件,然后返回每列的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50330203/