Randomizer

In this example we are discussing how to generate the random numbers by using the random() method of the Math class and change them into different random numbers by apply

Randomizer

In this example we are discussing how to generate the random numbers by using the random() method of the Math class and change them into different random numbers by apply

Randomizer

Randomizer

     

In this example we are discussing how to generate the random numbers by using the random() method of the Math class and change them into different random numbers by apply some mathematical operations onto them and display 10 random numbers on the console.

Description of program: 

In the given example first we are defining three class (by making them static) variables whose values can't be changed, then define a long type variable and also create a method Randomnumbergenerator(). After that we define a method randomFloat() that performs some calculation on that long type variable and returns a float value. Now we take randomInt() method and passes the max value upto which we want to generate the random numbers, this method rounds the float value returned by the randomFloat() method by using the round() method of the Math class. Now we generate a class TestRandom  to test the random number generated. In this class we create an object of the of the Randomizer class and print the values of the random numbers on the console.

 

public class Randomnumbergenrator {
  
  static final int first = 830844;
  static final int second = 39048;
  static final int third = 3840938;
  
  long randomnumber = 1;  
  
  public Randomnumbergenrator(long randomnumber) { 
  this.randomnumber = randomnumber;
  }
  
  public float randomFloat() {
  randomnumber = (randomnumber * second + third) % first;
  return (float)randomnumber/(float)first;
  }
  
  public int randomInt(int max) {
  return Math.round(max * randomFloat());
  }
}


Download of above program.

Here is the class TestRandom.java that test the random number generated.

 public class TestRandom {

  public static void main(String[] args) {

  System.out.println("Here are the numbers generated randomly upto 500");
  Randomizer random = new Randomizer(new java.util.Date().getTime());
  for(int i = 0; i < 10; i++)
  System.out.println(random.randomInt(500));
  }
 }

Here is the output:

C:\Examples>java TestRandom
Here are the numbers generated randomly upto 500
441
297
365
152
425
322
293
385
346
72

Download of this program.