2015-11-16 57 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++; 
    } 
}