Random integer within a range - Java java.util

Java examples for java.util:Random Int

Description

Random integer within a range

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    public static void main(String[] argv) throws Exception {
        int low = 2;
        int high = 2;
        System.out.println(Random(low, high));
    }/* www .j  ava  2s  .c  o m*/

    private static final Random rand = new Random();

    public static int Random(int low, int high) {
        int tmp = rand.nextInt(high + 1 - low);
        return tmp + low;
    }

    public static int[] Random(int low, int high, int num) {
        int[] array = new int[num];
        for (int i = 0; i < num; i++) {
            array[i] = Random(low, high);
            for (int j = 0; j < i; j++) {
                if (array[i] == array[j]) {
                    i--; // redo i
                    break;
                }
            }
        }
        return array;
    }
}

Related Tutorials