Can't fix a 'java.util.NoSuchElement' error [closed]
-
21-12-2019 - |
Question
I'm trying to make a program that generate either 'win' or 'lose' for a coin flip, output the data into a file, and read that data to calculate the average, but I'm getting a 'java.util.NoSuchElementException
' error. I'm not entirely sure why I'm getting this.. Help would be much appreciated.
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);
}
}
Solution
change inFile.next()
to inFile.nextLine()
also, you will want to change if (token.equalsIgnoreCase( "WIN!" ))
to if(token.contains("WIN!"))
as otherwise it will never pass (.equals
check to see if the entire line is "WIN!" and only "WIN!", .contains
checks to see if the line has "WIN!" in it.)
OTHER TIPS
In the reading loop you test for inFile.hasNextLine()
, but try to get the next token by inFile.next()
. However, having a next line does not necessarily mean that there is a next token.
Either change hasNextLine()
to hasNext()
, or change next()
to nextLine()
(provided that all tokens are on separate lines).