FAQ 4d
Updated: 1/10/00
>>>>>> How Do I make random numbers?
====================================
Create an instance of the Random() class, then use the nextInt() function to get numbers.
You will need to seed the Random object (give it a relatively random number to get
started), otherwise your sequence of random numberswill repeat.
Here is an example that draws 20 random numbers, using a class the extends the Random() class:
// 'RandApplet' code file
import java.applet.*;
import java.awt.*;
import java.util.*;
class RandApplet extends Applet {
MyRandom randMaker;
RandApplet(){
randMaker = new MyRandom();
}
public void paint(g){
int value;
for (int ix=0;ix<20;ix++) {
value = randMaker.rand(100); // a number from 0-99
g.drawString("val "+ix+" = "+value,10,12*ix);
}
}
}
class MyRandom extends Random {
MyRandom(){
super(System.currentTimeMillis()); // seed the number generator
}
int rand(int value){ // returns a number from 0 to (value-1)
int number = nextInt();
if (number<0) number = -number;
return number % value;
}
int dice6(){ // returns a six-sided die roll
return rand(6)+1;
}
int dice20(){ // returns a twenty sided die roll
return rand(20)+1;
}
int dice3x6(){ // returns the result of 3 six sided dice
return dice6() + dice6 + dice6();
}
}