1

这是我的代码:

import java.io.File;
import java.util.Random;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;

public class BottleCapPrize{

    public static void main(String args[]) throws IOException{

        // create .txt file
        PrintWriter outFile = new PrintWriter(new File("05.06 Desk Check.txt"));

        // create Scanner object
        Scanner in = new Scanner(System.in);

        // prompt user for number of trials
        System.out.print("Please enter how much times you want to perform the trial: ");

        // create variable for recieving input
        int input = in.nextInt();

        // create count variable
        int count = 1;

        // create range variable
        int range;

        // create average
        double average = 0.0;

        // create Random object
        Random random = new Random();

        // while loop for trials
        while(count <= input){

            // create Random range
            range = random.nextInt(5) + 1;

            // calculate average
            average += range;

            // increment count
            count++;
        }

        // calculate final average
        double finalAverage = average/count;

        // display final average
        System.out.println("The average of you winning the prize is: "
                + finalAverage);

        // display average in file
        outFile.println("The average of you winning the prize is: "
                + finalAverage);
    }
}

当我运行这个程序时,我希望它不仅在控制台上显示最终平均值,而且还显示在上面代码中创建的名为“05.06 DeskCheck.txt”的文件中,但是当我运行它时,它只显示 finalAverage在控制台中打开一个名为“05.06 Desk Check.txt”的空白文件。我该如何解决这个问题,以便它也会在文件中显示 finalAverage?

4

2 回答 2

2

您需要关闭PrintWriter以将内容刷新到文件中。尝试添加这个:

outFile.close();
于 2013-11-02T18:54:05.183 回答
2

我想你将不得不关闭文件..

outfile.close();
于 2013-11-02T18:55:07.827 回答