Reputation: 851
I'm currently having an issue where a 'while' loop is not executing. I set the loop condition to be true if an input text file has a next line. However, when I executed my program, the loop did not run. I confirmed this by adding a 'System.out.println(text)', and as I suspected, there was no text that resulted.
What issue is causing the loop to not execute?
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Random;
import java.util.Scanner;
public class BottleCapPrize
{
public static void main (String[] args) throws IOException
{
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File("guess.txt"));
Scanner inFile = new Scanner(new File("guess.txt"));
Random rand = new Random();
System.out.print("Enter number of trials: ");
int trials = in.nextInt();
int guess = 0;
int totalGuess = 0;
for (int trial = 0; trial < trials; ++trial)
{
guess = 0;
int winCap = rand.nextInt(5) + 1;
int guessCap = rand.nextInt(5) + 1;
++guess;
while (guessCap != winCap)
{
guessCap = rand.nextInt(5) + 1;
++guess;
}
outFile.println(guess);
}
while (inFile.hasNextLine())
{
String number = inFile.nextLine();
guess = Integer.parseInt(number);
totalGuess += guess;
System.out.println("This should print if while loop conditions set to true.");
}
double average = (double)totalGuess / trials;
System.out.println(totalGuess + " " + guess);
System.out.println("On average, it took " + average + " bottles to win.");
System.out.println();
inFile.close();
outFile.close();
}
}
Upvotes: 0
Views: 152
Reputation: 161
Make sure to flush the contents to guess.txt
file after you use outFile.println(guess)
by doing outFile.flush()
.
Upvotes: 3
Reputation: 417
The first step is to verify that your outer loop, the for loop is actually running as well. if trials happens to be 0 then your for loop will never run either, and you will never reach the while loop itself.
Upvotes: 0