【发布时间】:2016-01-18 06:10:39
【问题描述】:
我正在编写一个程序来从文本文件中读取数据(成绩),计算平均值,然后比较每个成绩并将数据分为两类:好和差(取决于低于或高于平均水平)
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream ("scores.txt");
Scanner read = new Scanner (fis);
int count=0, id;
double total=0,average, grade;
String line;
Scanner stringScanner;
while(read.hasNextLine()){
line = read.nextLine();
stringScanner = new Scanner(line);
id = stringScanner.nextInt();
while (stringScanner.hasNextDouble()){
total = total + stringScanner.nextDouble();
count++;
}
stringScanner.close();
}
average = total/count;
System.out.println("The average is : "+ average);
read.close();
fis = new FileInputStream ("scores.txt");
read = new Scanner (fis);
while(read.hasNextLine()){
line=read.nextLine();
stringScanner=new Scanner (line);
id = stringScanner.nextInt();
while (stringScanner.hasNextDouble()){
grade = stringScanner.nextDouble();
if(grade >= average){
FileOutputStream fos = new FileOutputStream("good.txt");
PrintWriter pr = new PrintWriter (fos);
pr.print(id + "/t"+ grade);
pr.println();
}
else if (grade<average){
FileOutputStream fos = new FileOutputStream("poor.txt");
PrintWriter pr = new PrintWriter (fos);
pr.print(id + "/t"+ grade);
pr.println();
}
else System.out.println("test");
}
stringScanner.close();
}
fis.close();
read.close();
System.out.println("Files have been created...");
}
我认为我在计算平均值方面做得很好(因为它输出正确)。但是,我在编写糟糕和良好的文本文件时遇到了麻烦,这些文件已创建但它们仍然为空。我怎样才能让程序写在这两个文件上,我的代码到底缺少什么? 谢谢。
编辑: 下面是 .txt 文件的样子:
206527 44.24
208530 75.38
207135 85.61
205241 91.51
204324 50.61
203357 68.28
202117 57.11
【问题讨论】:
-
能否提供txt文件!
-
已添加,更新:我刚刚使用数组解决了它。但是,我仍然很好奇,因为讲师可能需要以下内容:通过两次读取文件而不使用数组来解决。它发生了。 :)
-
我在下面提供的解决方案不正是您想要的吗?
标签: java if-statement fileinputstream fileoutputstream printwriter