So I am new to reading from files with Java and are trying to get this loop to keep reading from a file that the program has written to but it seems that every time I run the script the terminal seems to wait for me to input a value instead. And when I do just to see how it would behave I get a NoSuchElementException(). I'm not really sure what is happening but I know what that error means. It doesn't make sense to me why it is acting like that. It's been really driving me nuts.
import java.io.IOException; import java.io.PrintWriter; import java.io.File; import java.util.Scanner; import java.util.Random; public class BottleCapPrize { public static void main (String[] args) throws IOException { PrintWriter outFile = new PrintWriter(new File("BottleOpener.txt")); Scanner in = new Scanner(System.in); Scanner inFile = new Scanner(new File("BottleOpener.txt")); Random rand = new Random(); int trials; int winCap = (int)(Math.random()*5)+1; int lenCaps = 0; int totalCaps = 0; double avg; System.out.print("Enter number of trials: "); trials = in.nextInt(); for (int counter = 1; counter <= trials; counter++){ while (rand.nextInt(5)+1 != winCap){ lenCaps++; } outFile.println(lenCaps); lenCaps = 0; } outFile.close (); while (in.hasNext()){ totalCaps += inFile.nextInt(); //<- I GET THE ERROR HERE } System.out.println("AVG: ~" + (avg = (double)totalCaps/trials)); } }