我试图在文本文件中为每一行找到同一行的数字平均值。 例如,如果这是文本文件:
8.7 6.5 0.1 3.2 5.7 9.9 8.3 6.5 6.5 1.5
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
我想打印像:
For Competitor #1, the average is 5.8625
For Competitor #2, the average is 0.0000
For Competitor #3, the average is 1.0000
这是我的代码。
import java.io.*;
import java.util.*;
import java.text.*;
public class BaseClass
{
public static void main(String args[]) throws IOException
{
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMinimumFractionDigits(4);
fmt.setMaximumFractionDigits(4);
Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int maxIndx = -1;
String text[] = new String[1000];
while (sf.hasNext()) {
maxIndx++;
text[maxIndx] = sf.nextLine();
}
sf.close();
int contestant = 0;
for (int j = 0; j <= maxIndx; j++) {
Scanner sc = new Scanner(text[j]);
double scoreAverage = 0;
double a = 0;
double array[] = new double[1000];
contestant++;
if (j <= 10) {
a += sc.nextDouble();
array[j] += a;
} else {
Arrays.sort(array);
int i = 0;
while (i < 10) {
scoreAverage += array[i];
i++;
}
}
String s = fmt.format(scoreAverage);
double d = Double.parseDouble(s);
System.out.println("For Competitor #" + contestant + ", the average is " + d);
}
}
}
打印
For the Competitor #1, the average is 0.0
For the Competitor #2, the average is 0.0
For the Competitor #3, the average is 0.0
答案 0 :(得分:1)
你这里的问题太复杂了。以下片段足以让您实现您想要实现的目标。
以下是代码段:
public static void main (String[] args) throws Exception
{
Scanner in = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int counter = 0;
String line = null;
while(in.hasNext()) {
line = in.nextLine();
double sum = 0;
String[] splits = line.split(" ");
for(String s : splits) {
sum += Double.parseDouble(s);
}
System.out.println("For Competitor #" + (++counter)
+ ", the average is " + (sum/splits.length));
}
}
输出:
For Competitor #1, the average is 5.69
For Competitor #2, the average is 0.0
For Competitor #3, the average is 1.0