Reputation: 19
I'm writing a program that has a 1 in 5 chance to be correct and until it's correct it keeps going. It then should go and print the information to a file, however when I try to run it, it wont seem to run the second loop however many times I ask it to with the scanner. I need everything inside of the while loop to go the same amount of times as the for loop because I'm going to take it and find the percent average of how many times it takes to get the 20%. Any help on this topic would be greatly appreciated.
edit - The input that I'm giving to be specific is the variable trials, when I initiate the program if I set it to 1000 I expect to see the for loop repeat the loop and everything inside of it 1000 times.
edit 2 - I wanted to add what it was I'm going of off, I'm doing a project and here are my guidelines to go off of:
Print the result to the screen.
import java.util.Random; import java.util.Scanner; import java.io.IOException; import java.io.PrintWriter; import java.io.File; public class BottleCapPrize { 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 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 ( );
} }
Upvotes: 1
Views: 232
Reputation: 3349
You need to reset randomNum
every for loop iteration. Otherwise, the while loop will never be entered because randomNum
will still equal 1
from the previous iteration.
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();
}
}
Upvotes: 3