How to easily Generate Random Numbers in Java

In this tutorial, we Generate Random Number using Java Random class and Math.Random methods.
  • Generating Random Number Using Java
  • Example: Using Java Random Class
  • Example: Using Java Math.Random

  • Generating Random Number Using Java

    Well, Java does provide some interesting ways to generate java random numbers, not only for gambling but also several other applications especially related to gaming, security, maths etc.
    Let's see how it's done!!There are basically two ways to do it-
    • Using Randomclass (in package java.util).
    • Using Math.random java class (however this will generate double in the range of 0.0 to 1.0 and not integers).
    Let's look at them one by one -

    Example: Using Java Random Class

    First, we will see the implementation using java.util.Random-Assume we need to generate 10 random numbers between 0 to 100.
    import java.util.Random;
    public class RandomNumbers{
            public static void main(String[] args) {
             Random objGenerator = new Random();
                for (int iCount = 0; iCount< 10; iCount++){
                  int randomNumber = objGenerator.nextInt(100);
                  System.out.println("Random No : " + randomNumber); 
                 }
         }
    }
    An object of Random class is initialized as objGenerator. The Random class has a method as nextInt. This will provide a random number based on the argument specified as the upper limit, whereas it takes lower limit is 0.Thus, we get 10 random numbers displayed.

    Example: Using Java Math.Random

    Now, if we want 10random numbers generated java but in the range of 0.0 to 1.0, then we should make use of math.random()
    You can use the following loop to generate them-
    public class DemoRandom{
      public static void main(String[] args) {
        for(int xCount = 0; xCount< 10; xCount++){
          System.out.println(Math.random());
        }
      }
    }
    Now, you know how those strange numbers are generated!!!
  • Generating Random Number Using Java
  • Example: Using Java Random Class
  • Example: Using Java Math.Random
  • No comments:

    Post a Comment