我正在编写一个程序,它有五分之一的机会是正确的,并且在正确之前它会一直运行。然后它应该将信息打印到一个文件中,但是当我尝试运行它时,它似乎不会运行第二个循环,但是我多次要求它使用扫描仪。我需要 while 循环内的所有内容都与 for 循环运行相同的次数,因为我要使用它并找到获得 20% 所需次数的百分比平均值。非常感谢有关此主题的任何帮助。
编辑 - 我要具体给出的输入是变量试验,当我启动程序时,如果我将它设置为 1000,我希望看到 for 循环重复循环及其内部的所有内容 1000 次。
编辑 2 - 我想添加我要完成的内容,我正在做一个项目,这里是我的指导方针:
- 确定每个人必须打开多少个瓶盖才能找到获胜的瓶盖。 (这代表一次试验。)将此值打印到文本文件。
- 提示用户输入试验次数。进行至少 1000 次试验。
- 从输出文件中读回所有试验的数据。
- 计算为赢得奖品而打开的平均上限数。
将结果打印到屏幕上。
导入java.util.Random; 导入 java.util.Scanner; 导入java.io.IOException; 导入 java.io.PrintWriter; 导入java.io.文件; 公开课 BottleCapPrize { public static void main (String [ ] args) 抛出 IOException {
PrintWriter outFile = new PrintWriter(new File("EBoost Chance.txt")); Scanner in = new Scanner(System.in); Random rand = new Random(); System.out.print("How many trials will you run? "); int trials = in.nextInt(); int totalTrials = 0; int randomNum = 0; int winCounter = 0; int counter = 0; int bottleCap = 1; int max = 5; int min = 1; double percentage = 0.0; for (totalTrials = 0; totalTrials <= trials; totalTrials++) { counter = 0; winCounter = 0; while (randomNum != 1) { randomNum = rand.nextInt((max - min) + 1) + min; if (randomNum == 1) { winCounter++; counter++; outFile.println("You would win in " + counter + " bottles."); } else if (randomNum != 1) { counter++; } } } outFile.close ( );
}
最佳答案
您需要在每次 for 循环迭代时重置 randomNum
。否则,永远不会进入 while 循环,因为 randomNum
仍等于上次迭代的 1
。
import java.util.Random;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class Main
{
public static void main(String[] args) throws IOException
{
PrintWriter outFile = new PrintWriter(new File("EBoost Chance.txt"));
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.print("How many trials will you run? ");
int trials = in.nextInt();
int totalTrials = 0;
int bottleCap = 1;
int max = 5;
int min = 1;
double percentage = 0.0;
for (totalTrials = 0; totalTrials <= trials; totalTrials++)
{
int counter = 0;
int winCounter = 0;
int randomNum = 0; // this was moved from outside the for
while (randomNum != 1)
{
randomNum = rand.nextInt((max - min) + 1) + min;
if (randomNum == 1)
{
winCounter++;
counter++;
outFile.println("You would win in " + counter + " bottles.");
}
else if (randomNum != 1)
{
counter++;
}
}
}
outFile.close();
}
}
关于Java - 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988021/