Advertisement
Guest User

RandInt in Java

a guest
Mar 6th, 2015
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Random;
  2. //You need java.util.Random in otder to general random numbers
  3.  
  4. public static int randInt(int min, int max)
  5. {
  6.     //First, you create a new Random object
  7.     Random rand = new Random();
  8.     //Then, you get the next random integer; the range normally is from 0 to max, exclusive, so you add one
  9.     //After getting a random number, you add the minimum, so you stay within the range
  10.     //For example, rand.nextInt(3) might return 0 or 1 or 2, and you want something between 3 and 6; the smallest (0)
  11.     // should then have 3 added to it to stay in the range.
  12.     int randomNum = rand.nextInt((max - min) + 1) + min;
  13.     // Then you can return it
  14.     return randomNum;
  15. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement