我正在尝试制作一个程序,该程序为掷硬币生成“赢”或“输”,将数据输出到文件中,并读取该数据以计算平均值,但出现java.util.NoSuchElementException
“错误” 。我不完全确定我为什么会得到这个..帮助将不胜感激。
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
public static void main(String [] args) throws IOException
{
int random;
int loop = 1;
double trials = 0;
double winCounter = 0;
double average;
String token = "";
//
Scanner in = new Scanner(System.in);
Random rand = new Random();
PrintWriter outFile = new PrintWriter (new File("MonteCarloMethod.txt"));
//User Input Trials
System.out.print("Number of trials: ");
trials = in.nextInt();
//For loop (random, and print to file)
average = 0;
for(loop = 1; loop <= trials; loop++)
{
random = rand.nextInt(5);
if(random == 1)
{
outFile.println("Trial: " + loop + " WIN!");
}
outFile.println("Trial: " + loop + " LOSE");
}
outFile.close();
//read output
File fileName = new File("MonteCarloMethod.txt");
Scanner inFile = new Scanner(fileName);
while (inFile.hasNextLine())
{
token = inFile.next();
if (token.equalsIgnoreCase( "WIN!" ))
{
winCounter++;
}
}
//average and print average
average = winCounter / trials * 100;
outFile.println("Average number of caps to win: " + average);
System.out.println("Average number of caps to win: " + average);
}
}