我必須製作一個程序,要求用戶輸入幾個分數。每個分數都需要寫入文件「scores.txt」,但是當我輸入我的10個分數後,程序不會執行任何操作,分數也不會寫入文件。基本上,我不確定如何使用processFile來顯示平均分數。最終的程序應提示用戶獲得幾個分數,將分數寫入文件,然後打開該文件,計算平均值並顯示出來。我必須使用退出條件,如果它是否定的,它應該假設用戶輸入數據。Java寫入文件測試成績
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();
}
}
完美!非常感謝! :) –
@SikkiNixx非常感謝:-) –