what i am supposed to do is calculate the chances of wining a bottle top prize if there is one in five winners. i have to do it a difficult way though. i made a random number that signifies a win when it lands on one. i then have to output how many wins vs. loses to a file. next i have to import it back and use it to calculate how many drinks you would need to buy in order to win once, and print this to the screen. my problem is that once i bring the file back in i dont know how to use it to make the calculations. i have this much already so thats pretty much all i have left to do.

/**
 * 
 * 
 * Nathan Gibson 
 * 
 */
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class BottleCapPrize
{
    public static void main(String [] args)throws IOException
    {
        Scanner in;  
        in = new Scanner(System.in);
        
        int randomNumber = ((int)(0+ Math.random()* 5));
        int counter = 0;
        int winCounter = 0;
        
        
        PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));

        while(counter < 20)
        {

            randomNumber = ((int)(0+ Math.random()* 5));
            outFile.println("Wins: " + winCounter + " Total: " + counter);
            
            if (randomNumber == 1)
            {
            winCounter++;
            counter++;
            
            }
            else
            {
            counter++;
            }
        
            
        }
        
        outFile.close ( );
        
        String token = "";
        File fileName = new File("bottleCap.txt");
        Scanner inFile = new Scanner(fileName);
        while (inFile.hasNext())
        {
         UNKNOWN   
                  
        }      
      inFile.close();
        
        
        
       
    }
}

Example output is

run:
Wins: 0 Total: 0
Wins: 0 Total: 1
Wins: 0 Total: 2
Wins: 0 Total: 3
Wins: 0 Total: 4
Wins: 0 Total: 5
Wins: 1 Total: 6
Wins: 1 Total: 7
Wins: 1 Total: 8
Wins: 2 Total: 9
Wins: 2 Total: 10
Wins: 2 Total: 11
Wins: 2 Total: 12
Wins: 2 Total: 13
Wins: 2 Total: 14
Wins: 2 Total: 15
Wins: 2 Total: 16
Wins: 3 Total: 17
Wins: 4 Total: 18
Wins: 4 Total: 19

Reduce redundants ( in write phase )

0
0
0
0
0
0
1
1
1
2
2
2
2
2
2
2
2
3
4
4

Now you can know what to do

oh, okay i got what you are saying. that makes it alot simpler. how can i go about writing a statement to recognize the first "1" in the file and divide it by the number of zeros before it and then multiply by one hundred in order to calculate a percentage probability to describe the chance of winning the prize?

due to sequential nature of reading file simpler is introduce array int[5]
int readedInt;
and increase (+1) value at index of array[readedInt]
now array is ready to statistic analysis
Not to many stuff at same time.

the only problem with using arrays it this is an assignment, and we have not went over arrays, therefore i dont know them, or am i expected to know them. i have been looking for some type of method that would be suitable for this situation, but i havent found one. my problem is that i really dont understand how i am supposed to make the calculations with the file the i am inputting. my file looks like this:

0
0
0
1
1
2
2
2
2
3
3
4
4
4
4
4
4
4
5
5
5

what i need to do is divide the first number one by the number of zeros before it and then multiply by one hundred and that will give me the probability that i need, but i dont know if that is even a possible solution.

In place of array you can introduce six int varibles. i0,i1,i2,i3,i4,i5 and use "if" steatment
if(readedInt==0){
i0=i0+1;
}else if (readedInt==1){....

would this work in my situation with my loop? how would i know how many variables to set because the first match could take more than this first occurrence? with this technique how would i be able to make the first number 1 be divided by the number of zeros?

how many variables are needed?
Theoretically
maximum of counter < 20
no more than 20.
20, if randomNumber (always) == 1

well the reason i am saying is because we are supposed to test with 20 but the final assignment is supposed to have 200 tests to base it's probability on, so i dont know if doing it that way would be suitable.

If I understand the importance "Wins:". For me, "Wins:" is a player's ID and the number of this identifier is the number of his victories. In that case it would be to determine the number of players in the algorithm.
(google-translator)

wow. i think there is a discrepancy in our understanding of what each other means. i am simulating a drink contest with bottle tops. each bottle top has a one in five chance of winning. i have to create an output file that records the... wait never mind, here are the exact instructions:

1. Create a new project called 5.06 Monte Carlo Method in the
Mod05 Assignments folder.
2. Create a class called BottleCapPrize in the newly created
project folder.
3. Determine how many times a die must be rolled in order to
win a prize. (This represents one trial.) Print this value to a
text file.
4. Conduct at least 1,000 trials.
5. Read the data back in from all of the trials.
6. Calculate the average number of times a die must be rolled in order to win a prize.
7. Print the result to the screen.
Suggestion: Write this program in stages. First, work on the part that conducts trials and
print the results to the screen; however, during testing only use about 20 trials. Second,
print the results of each trial (the number of rolls to get a prize) to a file. Check the file to
verify it matches the screen output. Third, read the trial data back in and calculate the
average. Fourth, print the results.
Expected Output: When your program runs, your output should simply print a message
indicating the average number of bottles of Boost you would need to drink to win a prize

i have gotten pretty far, but it is the last part that is getting me. once i import the file back i don't exactly know how to use the imported numbers to calculate the probability that i need. the rest though i think i have done pretty correctly.

From your assignment spec:

  1. Create a new project called 5.06 Monte Carlo Method in the
    Mod05 Assignments folder.
  2. Create a class called BottleCapPrize in the newly created
    project folder.
  3. Determine how many times a die must be rolled in order to
    win a prize. (This represents one trial.) Print this value to a
    text file.
  4. Conduct at least 1,000 trials.
  5. Read the data back in from all of the trials.
  6. Calculate the average number of times a die must be rolled in order to win a prize.
  7. Print the result to the screen.

There is some very loose, inaccurate language in this assignment spec. You're stuck with it, but sometimes it drives me nuts when professors use incorrect terminology like this. The probability is KNOWN ahead of time and has nothing to do with any random rolls of a die. Similarly, the expected number of trials that it will take before you get your first winner is also known and can be calculated EXACTLY. Hence any random number generation would be an incorrect approach to this problem. Take words like "determine", "calculate", and "probability" with a grain of salt here. I commented in a similar vain regarding statistics/probability terminology last night to someone. Might have been another of your threads. Not sure. Anyway, end of sermon regarding terminology.

Regarding your problem, since in line 3, "trial" is defined as the number of times before you get a winner, your output file should look something like this:

6 3 7 2 6 8 10 [B]2[/B]

These should average to around 5. Read 'em all in and take the average. That's your answer to number 6. Your file is incorrect. You should have no zeroes. If you open ten bottles and the first nine aren't winners and the tenth is, you write this to the file:

1[B]0[/B]

not this:

0
0
0
0
0
0
0
0
0
[B]1[/B]

I can't think of any other way to read the spec.

In this case

Wins: 0 Total: 0
Wins: 0 Total: 1
Wins: 0 Total: 2
Wins: 0 Total: 3
Wins: 0 Total: 4
Wins: 0 Total: 5
Wins: 1 Total: 6 <----------
Wins: 1 Total: 7
Wins: 1 Total: 8
Wins: 2 Total: 9 <----------
Wins: 2 Total: 10
Wins: 2 Total: 11
Wins: 2 Total: 12
Wins: 2 Total: 13
Wins: 2 Total: 14
Wins: 2 Total: 15
Wins: 2 Total: 16
Wins: 3 Total: 17 <----------
Wins: 4 Total: 18 <----------
Wins: 4 Total: 19

only marked lines are important
where Wins: can be omitted ( always==1 winner)
and Total: can be a another counter, which can be setup to zero ,when the record is saved to a file.

From your assignment spec:

  1. Create a new project called 5.06 Monte Carlo Method in the
    Mod05 Assignments folder.
  2. Create a class called BottleCapPrize in the newly created
    project folder.
  3. Determine how many times a die must be rolled in order to
    win a prize. (This represents one trial.) Print this value to a
    text file.
  4. Conduct at least 1,000 trials.
  5. Read the data back in from all of the trials.
  6. Calculate the average number of times a die must be rolled in order to win a prize.
  7. Print the result to the screen.

There is some very loose, inaccurate language in this assignment spec. You're stuck with it, but sometimes it drives me nuts when professors use incorrect terminology like this. The probability is KNOWN ahead of time and has nothing to do with any random rolls of a die. Similarly, the expected number of trials that it will take before you get your first winner is also known and can be calculated EXACTLY. Hence any random number generation would be an incorrect approach to this problem. Take words like "determine", "calculate", and "probability" with a grain of salt here. I commented in a similar vain regarding statistics/probability terminology last night to someone. Might have been another of your threads. Not sure. Anyway, end of sermon regarding terminology.

Regarding your problem, since in line 3, "trial" is defined as the number of times before you get a winner, your output file should look something like this:

6 3 7 2 6 8 10 [B]2[/B]

These should average to around 5. Read 'em all in and take the average. That's your answer to number 6. Your file is incorrect. You should have no zeroes. If you open ten bottles and the first nine aren't winners and the tenth is, you write this to the file:

1[B]0[/B]

not this:

0
0
0
0
0
0
0
0
0
[B]1[/B]

I can't think of any other way to read the spec.

ohhhh, that makes perfect sense. your right. i have one more question though, in this part of the code

while(counter <= 20)
        {

            randomNumber = ((int)(0+ Math.random()* 5));
            outFile.println(winCounter); <----- what would i put here to make the output like what you described?
      
            
            if (randomNumber == 1)    <-------- how could i change this 
            {                                                     to represent what
                                                                   you described, would
                                                                   != work?  
            winCounter++;
            counter++;
            
            }
            else

alright, i think this may be the way to do what you were describing,

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));

        while(counter <= 20)
        {

            randomNumber = ((int)(0+ Math.random()* 5));
            outFile.println(winCounter);
            
            if (randomNumber == 1)
            {
            
            winCounter++;
            
            }
            
        
            
        }
        
        
        outFile.close ( );

it seems like that would keep it from printing out all those zeros, but now when i go to open the txt to look at the output notepad goes non-responding.

but sometimes it drives me nuts when professors use incorrect terminology like this.

dude i wish i had a professor, lol im taking ap computer science through a distance learning program at my high school. im a junior, and i have no teacher i can actually talk to. sadly that why im on these forums so much.

alright, i think this may be the way to do what you were describing,

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));

        while(counter <= 20)
        {

            randomNumber = ((int)(0+ Math.random()* 5));
            outFile.println(winCounter);
            
            if (randomNumber == 1)
            {
            
            winCounter++;
            
            }
            
        
            
        }
        
        
        outFile.close ( );

it seems like that would keep it from printing out all those zeros, but now when i go to open the txt to look at the output notepad goes non-responding.

You have an infinite loop here. counter never gets adjusted.

You need to step back and look at your program and do a redesign. For 20 trials, you will generate far more than 20 random numbers. You don't know how many numbers you'll need to generate, but the number of trials will be known (20, later to be 1000), so stick that in a for-loop.

Within each trial, you'll generate a random number and from that, decide whether you have a "winner". You've decided to have the range be 0 to 4 and have a winner declared if that number is 1. That's fine. When 1 shows up, that's the end of the trial, correct? Hence that needs to be somewhere in a while loop. For brevity's sake, let's say you have three trials. Let's say these are your random numbers. Note that you do not know in advance how many random numbers you'll need to produce. Here's one "run".

3
1
2
4
0
3
1
4
4
2
3
0
2
1

Lines 1 through 2 are trial 1. Lines 3 through 7 are trial 2. Lines 8 through 14 are trial 3. Your output file will be this:

2
5
[B]7[/B]

It took 2 tries for trial 1, 5 for trial 2, 7 for trial 3.

We're talking about a nested loop. How many trials? 3. That's an exact number known ahead of time, so we're talking about a for-loop. The inner loop is the trial itself. Do we know how many times that loop will be gone through in advance? No. While loop or Do-While loop. Is it guaranteed to occur at least once? Yes? Do-while loop (you could have a plain old while loop if you prefer). How do we know when the inner loop is done? When the random number is 1. Keep that in mind when thinking of the loop condition you need to write.

How many numbers are we outputting to the file? 3. This answer should help you place where to put the file output statement.

im getting very confused. i tried to follow your explanation and i somehow arrived at this:

for(int counter = 0; counter <= 20; counter++)
        {
            randomNumber = ((int)(0+ Math.random()* 5));

             while (randomNumber == 1 )
             {
                winCounter++; 
                counter++;
                outFile.println(loseCounter);
                
                while(randomNumber  == 2)
                {
                    
                    winCounter++;
                    counter++;
                
                    {
                        while (randomNumber  == 3)
                        {
                            winCounter++;
                            counter++;
                     
                                
                                while (randomNumber == 4)
                                {
                                    winCounter++;
                                    counter++;
                                    
                                    while (randomNumber == 5)
                                    {
                                        winCounter++;
                                        counter++;

that is probably entirely wrong. i modeled this more towards the counting the number of wrong so that i actually get the number it takes to get the prize, but my program is still doing the infinite loop thing and i cant look at the output.

oh i meant to move the outfile to the for loop and change all the wincounters on 2-5 to losecounters

ONE for-loop. ONE do-while loop inside of that for-loop. Here's a skeleton:

// create an output file and open it.


int numTrials = 20;

for (int i = 0; i < numTrials; i++)  // this is the start of your OUTER loop
{
  // create ONE counter variable and initialize it to 0
  int randomNumber = -1;  // initialize to some nonsense value.  This will be over-written.

  do  /* this is the start of your INNER loop */
  {
    // generate a random number and assign randomNumber to it
    // increment the counter variable.
  }
  while (randomNumber != 1); /* End of inner loop.  Do the inner loop while there is not a winner.  It's a winner if the random number is 1 */

  // write contents of the counter variable to the file.
} /* End of outer loop */

// close the output file

That's it! Not much code. ONE do-while loop inside of ONE for-loop. You have far too many loops.

thank you. my bad about the confusion. i was just really out in left field. thanks again for the help.

Looks like you are making good progress. After you get everything working, maybe rather than hard coding the number of trials, you want to prompt the user for this info. From your "Rolling Dice" post, it looks like you know how to use the scanner. Maybe it's too early yet, but as you continue programming, it's a good idea to start adding some "error" checking on user input. Here's an example:

Scanner in;  
in = new Scanner(System.in);
int numberOfTrials = 0;
boolean isValidInteger = false;

do{
       System.out.println("How many trials?: ");

       //check to see if data can be converted to integer
       if (in.hasNextInt()){
            //if data can be converted to integer, read the value
            numberOfTrials = in.nextInt();
            if (numberOfTrials < 1){
                System.out.println("Invalid number. Try again.");
                isValidInteger = false;
            }//if
            else{
                isValidInteger = true;
            }//else
        }//if
        else{
            //get invalid data and dispose of it
            in.next();
            System.out.println("Invalid data. Try again.");
            isValidInteger = false;
        }//else
}while(isValidInteger != true);

I think that I would use two "do-while" loops rather than a "for loop", because the trial isn't over until the random number generated = the winning number.

int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          //generate random number here

          rollCounter++;
          if (randomNumber == winningNumber){
              
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

Where do you want to increment the trialCounter? When is a trial considered complete?

I think that I would use two "do-while" loops rather than a "for loop", because the trial isn't over until the random number generated = the winning number.

int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          //generate random number here

          rollCounter++;
          if (randomNumber == winningNumber){
              
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

Where do you want to increment the trialCounter? When is a trial considered complete?

The trial is complete after your line 16, so increment trialCounter between lines 16 and 17. Any for-loop can be turned into a while (and often, a do-while) loop, as you have done. And any while loop can be turned into a for-loop. It's my personal preference to have loops where the number of iterations is known up front be for-loops.

I'm having trouble seeing how to do it with a for loop. Maybe you can provide an example. In my example, "trialCount++" would actually be inserted on line #13, since the trial is only complete when random number = winning number.

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));
int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               outFile.println(rollCounter);
               //winning number is found, this trial is complete
               trialCounter++;
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();

You can also add some debugging information.

int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

//change debugProgram to "true" if you want to see additional info
boolean debugProgram = false;

do{
     //re-initialize roll counter
     rollCounter = 0;
     if (debugProgram == true){
          outFile.println("Trial: " + trialCounter);
     }//if

     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               //print information to help in debugging
               if (debugProgram == true){
                    outFile.println("Roll Number: " + rollCounter + " Total Rolls: " + rollCounter + " Random Number: " + randomNumber);
                    outFile.println("");
               }//if
               else{
                    //used during normal operation
                    //when debugProgram = false;
                    outFile.println(rollCounter);
               }//else

               //winning number is found, this trial is complete
               trialCounter++;
          }//if
          else{
               //print information to help in debugging
               if (debugProgram == true){
                    outFile.println("       Roll Number: " + rollCounter + " Random Number: " + randomNumber );
               }//if
          }//else
 
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();

In my post earlier about using scanner, you can change the token delimiter as follows:

Scanner in;  
in = new Scanner(System.in);
in.useDelimiter("\n");

This changes the delimiter from the default of using white space, to using the newline character. To see the difference, when running my previous example and prompted for data enter "a b c". Do this without the line: in.useDelimiter("\n") and then with it and see the difference.

I'm having trouble seeing how to do it with a for loop. Maybe you can provide an example. In my example, "trialCount++" would actually be inserted on line #13, since the trial is only complete when random number = winning number.

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));
int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               outFile.println(rollCounter);
               //winning number is found, this trial is complete
               trialCounter++;
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();

Ok, I guess I made a mistake in this posting, you could place "trialCounter++" where VernonDozier said to place it, or you could place it where I placed it--either place should work.

Ok, I guess I made a mistake in this posting, you could place "trialCounter++" where VernonDozier said to place it, or you could place it where I placed it--either place should work.

If you stick your lines 14 and 16 after line 19, you can get rid of your if statement. Note that the condition that must be satisfied to execute the code inside of your if statement is exactly the same as the condition that must be satisfied to exit the inner do-while loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.