【发布时间】:2025-12-31 03:05:11
【问题描述】:
我正在尝试制作一个程序,该程序为掷硬币生成“赢”或“输”,输出数据到文件中,并读取该数据以计算 平均,但我收到“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);
}
}
【问题讨论】:
-
哪一行抛出
java.util.NoSuchElementException? -
能否包含完整的堆栈跟踪信息?
标签: java file loops random nosuchelementexception