2015-11-16 56 views
2

我需要讓用戶在循環中輸入10個分數,並將每個分數寫入文件「scores.txt」,但程序在輸入一個分數後終止。我不確定如何讓程序將10個分數中的每一個寫入文件。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) 
    { 
     score = sc.nextInt(); 
     outputWriter.write(score); } 
} 

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

您將'score'設置爲輸入。你並沒有將它用作計數器。這不斷輸入,直到分數低於10,而不是10分之後。 – Arc676

+0

以及任何負值將<= 10因此您的循環永不結束 – AbtPst

+0

您的退出條件是什麼?程序是否應該在取值10或用戶輸入負值後退出? – AbtPst

回答

1

您應該使用counter跟蹤輸入:

int count = 0; 
int score = 0; 
while (count < 10) { 
    score = sc.nextInt(); 
    if(score < 0) break; 
    outputWriter.write(score); 
    count++; 
} 

你所用做:

int score = 0; 
while (score <= 10) { 
    score = sc.nextInt(); 
    outputWriter.write(score); 
} 

只要您輸入的值大於10更大(我假設你是第一個輸入),循環將終止,條件爲score <= 10變爲false。你的問題的

+0

不正確地處理負分值輸入值 – ControlAltDel

+0

@ControlAltDel感謝您注意,糾正它。 – thegauravmahawar

0

部分是你使用的是相同的變量都會計算投入的數量和獲得輸入

int score = 0; 
    while (score <= 10) 
    { 
     score = sc.nextInt(); 
     outputWriter.write(score); } 
} 

會更好地使用不同的變量輸入,就像

int score = 0; 
    while (score <= 10) 
    { 
     int val = sc.nextInt(); 
     if (val < 0) break; 
     outputWriter.write(val); 
     score++; 
    } 
}