|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
||||
|
||||
|
getting Random ints
I built a class to model a six-sided dice. I am trying to build a reliable "roll()" function that will set the visible side according using the Random class in java.util.*.
I can instantiate a Random object, and get the range I want by doing a Random.nextInt(7), however I have observed that when I run this in a loop I do not get the psuedo-random distribution I would expect. Instead I get consectutive results that contain 2,3,4 and sometimes 5 of the SAME number in a row. Does anyone know how to rememdy this problem? Thanks. Brett |
|
#2
|
||||
|
||||
|
Ha! I am answering my own question...
The deal with java.util.Random is that it needs to be created as a class componant, and not inside a method. Otherwise, since it is psuedo random algorithm, you will get some not so random results if you recreate the object every time you call the method. Code:
package diceGame
import java.util.*;
public class RollableDice extends SixSidedDice
{
// constructor
public RollableDice()
{
super();
}
// command
public void roll()
{
this.setVisibleSide(this.randGenerator.nextInt(6)+1);
}
// componant
Random randGenerator = new Random(System.currentTimeMillis());
}
|
|
#3
|
|||
|
|||
|
Quote:
I have it in that situation for one of my scripts now Gotta fix that.
__________________
K1 |
|
#4
|
|||
|
|||
|
u can try this ...
r.nextInt(1000) % 7; i am sure..u will not have that repetition problems... if u r still not satisfied with the result try changin the 1000 to 10000... |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Java Help > getting Random ints |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|