Java examples for Language Basics:Random
Use the java.util.Random class to help generate the random numbers.
Make use of the Math.random() method.
import java.util.Random; public class Main { public static void main(String[] args) { // Create a new instance of the Random class Random random = new Random(); System.out.println("Random: " + random); // Generates a random Integer int myInt = random.nextInt(); System.out.println("Random int: " + myInt); // Generates a random Double value double myDouble = random.nextDouble(); System.out.println("Random double: " + myDouble); // Generates a random float float myFloat = random.nextFloat(); System.out.println("Random float: " + myFloat); // Generates a random Gaussian double // mean 0.0 and standard deviation 1.0 double gausDouble = random.nextGaussian(); System.out.println("Random Gaussian double: " + gausDouble); // Generates a random Long long myLong = random.nextLong(); System.out.println("Random long: " + myLong); // Generates a random boolean boolean myBoolean = random.nextBoolean(); System.out.println("Random boolean: " + myBoolean); double rand = Math.random(); System.out.println("Random double via Math: " + rand); }//from w w w . j a v a 2s . co m }