Generate random numbers using Math.random - Java Language Basics

Java examples for Language Basics:Random

Description

Generate random numbers using Math.random

Demo Code


public class Main {
 
  public static void main(String[] args) {
   // w ww  .j a v a  2 s. c o  m
    /*
     * This method returns a positive double value greater than 0.0
     * and less than 1.0
    */
   
    System.out.println("Random numbers between 0.0 and 1.0 are,");
    for(int i=0; i < 5 ; i++)
      System.out.println("Random Number ["+ (i+1) + "] : " + Math.random());
     
    /*
     * To generate random number between 1 to 100 use following code
     */
 
    System.out.println("Random numbers between 1 and 100 are,");
    for(int i=0; i < 5 ; i++)
      System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100));
   
  }
}

Result


Related Tutorials