Java's Random class:

  1. Java's library contains a very useful Random class used for simulation experiments: click here

  2. Creating Random objects:

    Example: creating a Random object:
          Random x = new Random();     
    

    Result:

  3. Instance methods in Random:

  4. Example: making fair dice

    Using Random object to create a fair Dice object
          public class Dice1
          {
             Random R;
    
             public Dice1()
             {
    	    R = new Random();
             }
    
             public int roll()
    	 {
    	    return( R.nextInt(6) + 1 );     
    	 }
          }
    
    

  5. Example: making LOADED dice

    Using Random object to create a loaded Dice object
          public class Dice2
          {
             Random R;
    
             public Dice2()
             {
    	    R = new Random();
             }
    
             public int roll()
    	 {
     	    int help;
    
    	    help = R.nextInt(10) + 1; // help is between 1 and 10
    
    	    if ( help > 6 )
    	       return(6);     // return 6 when help is 7, 8, 9 & 10
    	    else
    	       return( help );
    	 }
          }
    
    

  6. DEMO programs for your amusement: