无法修复'java.util.NoSuchElement'错误

时间:2014-01-10 07:52:33

标签: java file loops random nosuchelementexception

我正在尝试制作一个程序,为硬币翻转产生“赢”或“输”,输出将数据存入文件,并读取该数据以计算平均,但我收到了“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);

        }
    }

2 个答案:

答案 0 :(得分:3)

inFile.next()更改为inFile.nextLine()

另外,您需要将if (token.equalsIgnoreCase( "WIN!" ))更改为if(token.contains("WIN!")),否则它将永远不会通过(.equals检查整行是否为“WIN!”并且只有“赢! “,.contains检查线条中是否有”WIN!“。)

答案 1 :(得分:0)

在阅读循环中,您测试inFile.hasNextLine(),但尝试通过inFile.next()获取下一个标记。但是,拥有下一行并不一定意味着存在下一个令牌。

hasNextLine()更改为hasNext(),或将next()更改为nextLine()(前提是所有令牌都在不同的行上)。