Returns a random int between min Val and max Val - Java java.util

Java examples for java.util:Random Int

Description

Returns a random int between min Val and max Val

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int maxVal = 2;
        System.out.println(getRandom(maxVal));
    }//from w  ww. j  a  v a2 s.c  o  m

    /**
     * Returns a random int between minVal and maxVal
     * @param maxVal the upper limit of possible values
     * @param minVal the lower limit of possible value 
     * @return an random int between minVal and maxVal, if maxVal >=minVal. Otherwise, returns 0.  
     */
    public static int getRandom(int maxVal, int minVal) {
        int range = maxVal - minVal;
        if (range < 0) {
            return 0;
        }
        return (int) Math.round(Math.random() * range + minVal);
    }

    /**
     * Returns a random int between 0 and maxVal
     * @param maxVal the upper limit of possible values 
     * @return an random int between 0 and maxVal, if maxVal >0. Otherwise, returns 0. 
     */
    public static int getRandom(int maxVal) {
        return getRandom(maxVal, 0);
    }
}

Related Tutorials