简体   繁体   English

为什么我的Java程序跳过“ while”循环?

[英]Why is my Java program skipping a 'while' loop?

I'm currently having an issue where a 'while' loop is not executing. 我目前遇到“ while”循环未执行的问题。 I set the loop condition to be true if an input text file has a next line. 如果输入文本文件具有下一行,则将循环条件设置为true。 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. 我通过添加'System.out.println(text)'确认了这一点,并且我怀疑没有文本产生。

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. 第一步是验证您的外部循环, for循环是否也正在运行。 if trials happens to be 0 then your for loop will never run either, and you will never reach the while loop itself. 如果试验恰好为0,则您的for循环将永远不会运行,并且您也永远不会到达while循环本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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