我必须制作一个程序,要求用户输入几个分数。每个分数都需要写入文件“scores.txt”,但在输入我的10个分数后,程序不会执行任何操作,并且分数不会写入文件。基本上,我不确定如何使用processFile来显示平均分数。最终程序应提示用户输入几个分数,将分数写入文件,然后打开该文件,计算平均值并显示它。我必须使用退出条件,如果它是否定的,它应该假定用户输入了数据。
public class MoreTestScores {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
writeToFile("scores.txt");
processFile("scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter("scores.txt"));
System.out.println("Please enter 10 scores.");
System.out.println("You must hit enter after you enter each score.");
Scanner sc = new Scanner(System.in);
int score = 0;
while (score <= 10) {
int val = sc.nextInt();
if (val < 0) break;
outputWriter.write(val);
score++;
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException {
double sum = 0;
double number;
double average;
double count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("scores.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
number = Double.parseDouble(line);
sum += number;
count ++;
}
average = sum/count;
System.out.println(average);
inputReader.close();
}
}
答案 0 :(得分:1)
我可以看到2个问题。
int
值。这个方法是为了
写一个字符,而不是整数。见java doc
因此,您需要将值写为String
,以便回读为String
所以请更改while
循环中的编写代码,如下所示:
outputWriter.write(String.valueOf(val));
outputWriter.newLine();
答案 1 :(得分:0)
请在PrintWriter
(我已测试过代码)中使用writeToFile()
:
public static void writeToFile(String filename) throws IOException {
PrintWriter outputWriter = new PrintWriter("scores.txt");
System.out.println("Please enter 10 scores.");
System.out.println("You must hit enter after you enter each score.");
Scanner sc = new Scanner(System.in);
int score = 0;
while (score < 10) {
int val = sc.nextInt();
if (val < 0)
break;
outputWriter.println(val);
score++;
}
outputWriter.flush();
outputWriter.close();
}