Generate Random Numbers

The Math class provides the random method. The random method generates a double value greater tha or equal to 0.0 but less than 1.0.

 

If Random truly produces values at random, every value greater than or equal to 0.0 but less than 1.0 has an equal chance(or probability) of being chosen each time random is called.

We must multiply the random number by a scaling factor(in this case, 6(*6)) to scale correctly. The integer(int) cast operator is used to truncate the floating –point part(the part after the decimal point) of each value produced by the preceding expression.We then shift the range of numbers produced by adding 1 (1+(int)(Math.random()*6) to our previous result.

//Generate Random Numbers

import javax.swing.*;

public class RandomInt

 {

    public static void main(String aargum[])

      {

        int value;

        String output=" ";

        for(int i=1;i<=20;i++)

           {

            value=1+(int)(Math.random()*6);

            output+=value+" ";

            if(i%5==0)

                 output+="\n";

           }

        JOptionPane.showMessageDialog(null,output,

                 "20 Random Number from 1 to 6", 

                 JOptionPane.INFORMATION_MESSAGE);

        System.exit(0);

      }//main() ends

  }//class end

Output....

Generate Random Numbers