Welcome to Home.

Monday, August 6, 2018

GENERATE RANDOM NUMBERS | JAVA

In programming language, random numbers are required often. Random number can be used to set unique ids for user, for extracting data based on random number, for games etc. So,In JAVA programming language we can make use of Math class to generate random numbers. In this program I have generated 5 random numbers between 1 to 100. You can generate as per you wish by modifying few values.


class RandomDemo{

      public static void main(String args[]){

          for(int i=1;i<=5;i++){

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

          }

    }

}

Here, random method of Math class is called.
If you want random number between 1000 then simply multiply by that number.

For random Number between 0 to N.

Math.random()*N

It returns value in decimal form so i have typecasted decimal value into integer.

Also, I have used looping for 5 times which gives me 5 random numbers, if you want 10 simply write 10 instead of 5.



No comments:

Post a Comment