digrach

Using the Random class to generate a random int

Mar 8th, 2014
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3.  
  4. public class MyRandomExample {
  5.    
  6.     public static void main(String args[]) {
  7.        
  8.         for (int x = 0; x < 20; x ++) {
  9.             getRandomNum(); // any number.
  10.             getRandomNumWithMax(5); // number 0 - 4.
  11.                         getRandomNumWithMaxInclusive(5);  // number 0 - 5.
  12.             getRandomNumWithMinAndMax(100, 105); // number 100 - 104.
  13.                         getRandomNumWithMinAndMaxInclusive(100, 105); // number 100 - 105.
  14.         }
  15.     }
  16.    
  17.     public static void getRandomNum() {
  18.                 // Will return any number in the int range.
  19.         Random r = new Random();
  20.         int randomNum = r.nextInt();
  21.         System.out.println("Random number is: " + randomNum);
  22.     }
  23.    
  24.     public static void getRandomNumWithMax(int max) {
  25.                 // Will return a number inclusive of zero, up to but exclusive of max.
  26.         Random r = new Random();
  27.         int randomNum = r.nextInt(max);
  28.         System.out.println("Random number with max is: " + randomNum);
  29.     }
  30.  
  31.         public static void getRandomNumWithMaxInclusive(int max) {
  32.                 // Will return a number inclusive of zero, up to and inclusive of max.
  33.         Random r = new Random();
  34.         int randomNum = r.nextInt(max + 1);
  35.         System.out.println("Random number with max inclusive is: " + randomNum);
  36.     }
  37.    
  38.     public static void getRandomNumWithMinAndMax(int min, int max) {
  39.                 // Will return a number inclusive of min, up to but exclusive of max.
  40.         Random r = new Random();
  41.         int randomNum = r.nextInt(max - min) + min;
  42.         System.out.println("Random number with min and max is: " + randomNum);
  43.     }
  44.  
  45.         public static void getRandomNumWithMinAndMaxInclusive(int min, int max) {
  46.                 // Will return a number inclusive of min, up to and inclusive of max.
  47.         Random r = new Random();
  48.         int randomNum = r.nextInt((max - min) + 1) + min;
  49.         System.out.println("Random number with min and max inclusive is: " + randomNum);
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment