Title: Computer Science 209
1Computer Science 209
2Random Numbers
System.out.println((int)(Math.random() 6)
1) System.out.println((int)(Math.random() 6)
1)
Math.random() uses a single generator that is
seeded at the startup of the JVM. The seed is
calculated as a function of the computers
clock Kind of a pain to use to obtain random
integers
3java.util.Random
java.util.Random generator new
java.util.Random() System.out.println(generator.
nextInt(6) 1) System.out.println(generator.nex
tInt(6) 1) System.out.println(generator.nextDo
uble()) System.out.println(generator.nextBoolean
())
The Random class is much more convenient to
use A Random object is also seeded from the clock
4java.util.Random
java.util.Random generator1 new
java.util.Random() java.util.Random generator2
new java.util.Random() System.out.println(gene
rator1.nextInt(6) 1) System.out.println(genera
tor2.nextInt(6) 1)
If distinct Random objects are seeded during the
same millisecond, they will get the same seed and
generate the same pseudo-random sequence
5Rolling a Die
import java.util.Random public class Die
private int value private Random generator
public Die() value 0 generator
new Random() public void roll()
value generator.nextInt(6) 1
public String toString() return ""
value
6Rolling a Die
private Die die1 new Die() private Die die2
new Die() public DiceApp() setTitle("Roll
the Dice") diceField1.setEditable(false)
diceField2.setEditable(false)
rollButton.addActionListener(new
ActionListener() public void
actionPerformed(ActionEvent e)
die1.roll() die2.roll()
diceField1.setText(die1.toString
()) diceField2.setText(die2.toString())
) Container c
getContentPane() JPanel panel new
JPanel() panel.add(diceField1)
panel.add(diceField2) c.add("Center",
panel) c.add("South", rollButton)
7Two Wont Work
- The two dice are created within a millisecond of
each other, so their random number generators
produce the same sequence of numbers - We need a way of sharing one instance of Random
among all dice
8The Context of the Singleton Pattern
- All clients need to share a single instance of a
class - No additional instances can be created
accidentally
9Solution of the Singleton Pattern
- Define a class with a private constructor
- The class constructs a single instance of itself
- The class includes a static method to return the
single instance
10A Better Random
import java.util.Random public class
SingleRandom private static SingleRandom
instance new SingleRandom() private Random
generator private SingleRandom()
generator new Random() public int
nextInt(int limit) return
generator.nextInt(limit) public static
SingleRandom getInstance() return
instance
11A Better Die
public class BetterDie private int value
private SingleRandom generator public
BetterDie() value 0 generator
SingleRandom.getInstance() public void
roll() value generator.nextInt(6) 1
public String toString() return ""
value