我的代码可以读取名为“ QuizScores.txt”的文件中的数字列表。但是,在此文件中,某些数字包含字母。我告诉我的程序只需忽略那些实例并移至下一个数字。现在的问题是,我的代码一次只需要读取一行来查看整个文件,然后将其读入,计算平均值,最大值和最小值,最后将其输出到名为“ QuizStats.txt”。任何帮助,将不胜感激!谢谢!
测验分数:
45
63
74g
34.7
75
4
8
15
16
23
42
67f
34
67
码:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
try{
double num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
} catch( NumberFormatException err )
{
}
}
System.out.println(sum);
}
} catch (IOException err) {
err.printStackTrace();
}
catch (NumberFormatException err) {}
finally {
try {
if (reader != null){
reader.close();
}
}
catch (IOException err) {
err.printStackTrace();
}
}
}
}
最佳答案
试试这个代码
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
double average = 200.0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
int n = 1;
String currentLine;
double c;
try {
reader = new BufferedReader(new FileReader("QuizScores.txt"));
System.out.println("--Quiz Scores--");
while ((currentLine = reader.readLine()) != null) {
try {
c = Double.parseDouble(currentLine);
} catch (Exception ex) {
continue;
}
max = max > c ? max : c;
min = min < c ? min : c;
average += (c - average) / n;
n++;
System.out.println(c);
}
System.out.println("--Summary--");
System.out.println("Average: " + average);
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出量
--Quiz Scores--
45.0
63.0
34.7
75.0
4.0
8.0
15.0
16.0
23.0
42.0
67.0
34.0
67.0
--Summary--
Average: 37.97692307692308
Minimum: 4.0
Maximum: 75.0
这是你想要的?