我需要让用户在一个循环中输入10个分数并将每个分数写入文件" scores.txt",但程序在我输入一个分数后终止。我不知道如何让程序将10个分数中的每一个写入文件。
最终程序应该提示用户输入几个分数,将分数写入文件,然后打开该文件,计算平均值并显示它。
循环的退出条件可以是负分;如果是否定的,我可以假设用户已完成输入数据。
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 :(得分: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
时终止。
答案 1 :(得分: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++;
}
}