# Thread: java.util.Random problem

1. Member
Join Date
Nov 2015
Posts
1
Rep Power
0

## java.util.Random problem

I wrote a program that essentially flips a coin until heads is flipped consecutively the inputted amount of times. The program worked sometimes, and sometimes is didn't, so I wrote a statement that outputs the number of flips every 10000 flips. When the program runs as intended, the final output is usually around 15000, but sometimes it rockets off into the millions and I have to manually end the program. Why is this? The program is below(sorry for the useless variables).

import java.util.Random;
import java.util.Scanner;
public class CoinFlipper{
public static void main(String[] args){

Scanner in=new Scanner(System.in);
System.out.println("Enter a number:");
int b=in.nextInt();

long z=0;
int c=0;
int d=0;

while(c<b)
{
{
Random generator=new Random();
int a=generator.nextInt(50)+1;
if(a<=25)
{
d++;
c++;
}

if(a>25)
{
int f=b-5;
int e=d;
c=0;
d=0;
}
z++;
}
if(z%10000==0)
{
System.out.println(z);
}
}

System.out.println("The program has flipped heads "+b+" times in a row after flipping the coin "+z+" times");

}
}

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: java.util.Random problem

I believe that 15000 is too few (although statistically you could do it in the first 25 flips). The odds are 2^n where n is the number of heads or tails in a row. You also, only need to create one instance of Random (before you enter the loop).

Regards,
Jim

3. ## Re: java.util.Random problem

final output is usually around 15000
Wouldn't the number of flips depend on the number in a row requested?

sorry for the useless variables
Yes, the names of the variables are useless. Poorly named variables make a program much harder to understand both for the reader and the writer of the code.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•