My project entails that I create a basic number guessing game that uses the JOptionPane and does not use Math.Random to create the random value. How would you go about doing this? I've completed everything except the random number generator. Thanks!
4 Answers
Here the code for a Simple random generator:
public class SimpleRandom { /** * Test code */ public static void main(String[] args) { SimpleRandom rand = new SimpleRandom(10); for (int i = 0; i < 25; i++) { System.out.println(rand.nextInt()); } } private int max; private int last; // constructor that takes the max int public SimpleRandom(int max){ this.max = max; last = (int) (System.currentTimeMillis() % max); } // Note that the result can not be bigger then 32749 public int nextInt(){ last = (last * 32719 + 3) % 32749; return last % max; } } The code above is a "Linear congruential generator (LCG)", you can find a good description of how it works here.
Disclamer:
The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.
2 Comments
If you don't like the Math.Random you can make your own Random object.
import:
import java.util.Random; code:
Random rand = new Random(); int value = rand.nextInt(); If you need other types instead of int, Random will provide methods for boolean, double, float, long, byte.
1 Comment
You could use java.security.SecureRandom. It has better entropy.
Also, here is code from the book Data Structures and Algorithm Analysis in Java. It uses the same algorithm as java.util.Random.
Randomclass, lol.