Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class MyRandomExample {
- public static void main(String args[]) {
- for (int x = 0; x < 20; x ++) {
- getRandomNum(); // any number.
- getRandomNumWithMax(5); // number 0 - 4.
- getRandomNumWithMaxInclusive(5); // number 0 - 5.
- getRandomNumWithMinAndMax(100, 105); // number 100 - 104.
- getRandomNumWithMinAndMaxInclusive(100, 105); // number 100 - 105.
- }
- }
- public static void getRandomNum() {
- // Will return any number in the int range.
- Random r = new Random();
- int randomNum = r.nextInt();
- System.out.println("Random number is: " + randomNum);
- }
- public static void getRandomNumWithMax(int max) {
- // Will return a number inclusive of zero, up to but exclusive of max.
- Random r = new Random();
- int randomNum = r.nextInt(max);
- System.out.println("Random number with max is: " + randomNum);
- }
- public static void getRandomNumWithMaxInclusive(int max) {
- // Will return a number inclusive of zero, up to and inclusive of max.
- Random r = new Random();
- int randomNum = r.nextInt(max + 1);
- System.out.println("Random number with max inclusive is: " + randomNum);
- }
- public static void getRandomNumWithMinAndMax(int min, int max) {
- // Will return a number inclusive of min, up to but exclusive of max.
- Random r = new Random();
- int randomNum = r.nextInt(max - min) + min;
- System.out.println("Random number with min and max is: " + randomNum);
- }
- public static void getRandomNumWithMinAndMaxInclusive(int min, int max) {
- // Will return a number inclusive of min, up to and inclusive of max.
- Random r = new Random();
- int randomNum = r.nextInt((max - min) + 1) + min;
- System.out.println("Random number with min and max inclusive is: " + randomNum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment