Generating Random Numbers in Java

 



Java’s Math class has an easy to use random number generator.

Math.random();

This method creates a random double value greater than or equal to zero but less than one.

Here is an example:


public class RandomNumber {

  public static void main(String[] args) {

    //random number

    System.out.println(Math.random());

  }

}


If cast as an int, you can generate many different useful values.

    //random number 0 to 9

    System.out.println((int)(Math.random()*10));


    //random number 1 to 3

    System.out.println((int)(Math.random()*3)+1);

   

    //random number -10 to 10

    System.out.println((int)(Math.random()*21)-10);

    

    //random number 2 to 10 even numbers only

    System.out.println((int)(Math.random()*5)*2+2);



Comments

Popular Posts