2015-11-17 48 views
2

我必須製作一個程序,要求用戶輸入幾個分數。每個分數都需要寫入文件「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(); 
    } 
} 

回答

0

請在writeToFile()(我已經測試的代碼),而不是使用PrintWriter

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(); 
} 
+1

完美!非常感謝! :) –

+0

@SikkiNixx非常感謝:-) –

1

2個問題,我可以看到。

  • 您正在編寫int值。這種方法是爲了 編寫一個性格特徵,而不是一個integer.See java doc 所以你需要爲了讀回String
  • 你是不是寫在每個line.But閱讀作爲個體的每個值寫入值String

所以,請更改編輯代碼中while循環如下:

outputWriter.write(String.valueOf(val)); 
outputWriter.newLine();