我正在编写一个程序,该程序进入基本.txt文件并打印某些内容。它是逗号分隔的文件。该文件包括7个名字和姓氏,以及之后的4个数字。七个中的每一个都在一个单独的行上。
每一行都是这样的:
George Washington,7,15,20,14
程序必须抓住姓氏然后平均4个数字,但也要平均所有7个中的第一个,所有7个中的第二个等等。我不确定如何开始接近它并让它保持抓住并打印出必要的东西。谢谢你的帮助。我很感激。我正在使用Mac来完成所有这些编程,它需要在Windows上运行,所以我正在使用:
File Grades = new File(System.getProperty("user.home"), "grades.txt");
那么如何使用它来读取文件呢?
答案 0 :(得分:2)
Java的File类实际上并不处理您的开放或阅读。您可能需要查看FileReader和BufferedReader类。
答案 1 :(得分:-1)
不要担心它是在Mac还是Windows上运行。 Java会为您处理所有业务。 :)
您可以执行以下操作。这只是一个快速的解决方案,所以你可能想要做一些改变。它现在从名为“input.txt”的文件中读取。
import java.io.*;
public class ParseLines {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("input.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(new DataInputStream(fs)));
String line;
double collect[] = {0.0, 0.0, 0.0, 0.0};
int lines = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 5) {
int avg = 0;
boolean skip = false;
for (int i = 1; i < 5; i++) {
String part = parts[i].trim();
try {
int num = Integer.valueOf(part);
avg += num;
collect[i - 1] += (double) num;
}
catch (NumberFormatException nexp) {
System.err.println("Input '" + part +
"' not a number on line: " + line);
skip = true;
break;
}
}
if (skip) continue;
avg /= 4;
lines++;
System.out.println("Last name: " + parts[0].split(" ")[1] +
", Avg.: " + avg);
}
else {
System.err.println("Ignored line: " + line);
}
}
for (int i = 0; i < 4; i++) {
collect[i] /= (double) lines;
System.out.println("Average of column " + (i + 1) + ": " +
collect[i]);
}
reader.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
修改:修改代码以平均第一,第二,第三和第四列。