无法修复“java.util.NoSuchElement”错误[关闭]
-
21-12-2019 - |
题
我正在尝试制作一个程序,为抛硬币生成“赢”或“输”, 输出 将数据写入文件,并读取该数据以计算 平均的, ,但我得到了'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);
}
}
解决方案
改变 inFile.next()
到 inFile.nextLine()
另外,你会想要改变 if (token.equalsIgnoreCase( "WIN!" ))
到 if(token.contains("WIN!"))
否则它永远不会通过(.equals
检查整行是否是“赢!”只有“赢!”, .contains
检查该线是否有“获胜!”在里面。)
其他提示
在您测试的阅读循环中 inFile.hasNextLine()
, ,但尝试通过以下方式获取下一个令牌 inFile.next()
. 。然而,有下一行并不一定意味着有下一个标记。
要么改变 hasNextLine()
到 hasNext()
, ,或改变 next()
到 nextLine()
(前提是所有标记都位于单独的行上)。
不隶属于 StackOverflow