skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, January 7, 2012

Generate Random Number Using Math.Random Function in JAVA

Posted by Admin at 1:18 AM – 0 comments
 
Here is Program to Get a Random Number between 0 to Passed Argument
public class RandomInt { 
    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);

        // a pseudo-random real between 0.0 and 1.0
        double r = Math.random(); 

        // a pseudo-random integer between 0 and N-1
        int n = (int) (r * N);

        System.out.println("Your random integer is: " + n);
    }
}

/*************************************
 *  % java RandomInt 100
 *  Your random integer is: 55
 *
 *  % java RandomInt 100
 *  Your random integer is: 3
 *
 *************************************/


Explanation of Random Number Program:
In this Java Random Program, we have one argument for number and then we are generating random number using Math.random() function.
Math.random() function always generate the value between 0 to 1 so if you want to generate the value different than this then you should multiply your number to Random Generated Value.
 After multiplying the number with Generated Random number we will get the our Random Number.
Labels: Basic Java Programs , Random Function

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger