954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

file output/ input & file handling

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();
        
        
        
       
    }
}
gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

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?

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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.

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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){....

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

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?

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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)

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

From your assignment spec:
Create a new project called 5.06 Monte Carlo Method in the
Mod05 Assignments folder.
Create a class called BottleCapPrize in the newly created
project folder.
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.
Conduct at least 1,000 trials.
Read the data back in from all of the trials.
Calculate the average number of times a die must be rolled in order to win a prize.
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 <strong>2</strong>


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<strong>0</strong>


not this:

0
0
0
0
0
0
0
0
0
<strong>1</strong>


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

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

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.

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 
From your assignment spec:
  • Create a new project called 5.06 Monte Carlo Method in the Mod05 Assignments folder.
  • Create a class called BottleCapPrize in the newly created project folder.
  • 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.
  • Conduct at least 1,000 trials.
  • Read the data back in from all of the trials.
  • Calculate the average number of times a die must be rolled in order to win a prize.
  • 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 <strong>2</strong>

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<strong>0</strong>

not this:

0
0
0
0
0
0
0
0
0
<strong>1</strong>

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
gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 
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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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
<strong>7</strong>


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.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

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.

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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

gibson.nathan
Junior Poster in Training
89 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You