Advertisement
CMNatic

RNG Java

Dec 20th, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. /** Generate random integers in a certain range. */
  4. public final class randomnum {
  5.  
  6.   public static final void main(String... aArgs){
  7.     log("Generating random integers in the range 1..10.");
  8.    
  9.     int START = 1;
  10.     int END = 49;
  11.     Random random = new Random();
  12.     for (int idx = 1; idx <= 49; ++idx){
  13.       showRandomInteger(START, END, random);
  14.     }
  15.    
  16.     log("Done.");
  17.   }
  18.  
  19.   private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
  20.     if (aStart > aEnd) {
  21.       throw new IllegalArgumentException("Start cannot exceed End.");
  22.     }
  23.     //get the range, casting to long to avoid overflow problems
  24.     long range = (long)aEnd - (long)aStart + 1;
  25.     // compute a fraction of the range, 0 <= frac < range
  26.     long fraction = (long)(range * aRandom.nextDouble());
  27.     int randomNumber =  (int)(fraction + aStart);    
  28.     log("Generated : " + randomNumber);
  29.   }
  30.  
  31.   private static void log(String aMessage){
  32.     System.out.println(aMessage);
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement