這裏是我的代碼:使用Java語言編寫的文件,找到finalAverage
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?