# Thread: Need to generate a random number between 1-3 inclusive

1. Member
Join Date
Feb 2013
Posts
63
Rep Power
0

## post increment for a variable doesn't seem to be working

Below is a code where at the very end I need winBySwitch to increase by 1 each time newGuess = prize. It seems to be doing so, i.e incrementing, because I checked by placing a print statement
for the winBySwitch within the for loop. But for some reason when it displays the probabOfWinBySwitch = winBySwitch / numOfPlays value it shows up as 0. What could be the problem here?

Java Code:
```int winBySwitch = 0;
double probabOfWinBySwitch = winBySwitch / numOfPlays;
double probabOfWinWOSwitch =  ( 1 - probabOfWinBySwitch );

for(int i = 0; i < numOfPlays; i++)
{
// Generate random num for door with prize

int prize = randomGenerator.nextInt(4);

while( prize == 0 )
{
prize = randomGenerator.nextInt(4);
}

// Generate random num for contestant's guess

int guess = randomGenerator.nextInt(4);

while(guess == 0 )
{
guess = randomGenerator.nextInt(4);
}

// Generate random num for door to be opened

int view = randomGenerator.nextInt(4);

while(view == 0 && view != guess && view != prize )
{
view = randomGenerator.nextInt(4);
}
// Generate new guess for contestant

int newGuess = randomGenerator.nextInt(4);

while(newGuess == 0 && newGuess != guess && newGuess != view )
{
newGuess = randomGenerator.nextInt(4);
}

//compare the new guess with the prize door num
if( newGuess == prize)
{
winBySwitch++;
}

System.out.printf("%5d", prize);
System.out.printf("%12d", guess);
System.out.printf("%12d", view);
System.out.printf("%13d\n", newGuess);

}

System.out.println("\nProbability of winning if you switch = " + probabOfWinBySwitch );
System.out.print("Probability of winning if you do not switch = " + probabOfWinWOSwitch);

}```
Last edited by abi; 03-11-2013 at 06:43 PM.

2. ## Re: Need to generate a random number between 1-3 inclusive

Take a look at the API for Random. What does that 10 you pass into the nextInt() method do?

As for your second code snippet, be mindful of what you're converting to an int.

3. Member
Join Date
Feb 2013
Posts
63
Rep Power
0

## Re: Need to generate a random number between 1-3 inclusive

Ok, I see. I am a beginner and I wasn't aware that the value that I passed would be for a exclusive range.

Thank You.

#### Posting Permissions

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