简体   繁体   中英

Why is my Java program skipping a 'while' loop?

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();

}
}

在使用outFile.println(guess)之后,请确保通过执行outFile.flush()将内容刷新guess.txt文件。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM