Java Random Int randomWithRange(int min, int max)

Here you can find the source of randomWithRange(int min, int max)

Description

Method for generating random integer between the 2 parameters, The order of min and max do not matter.

License

LGPL

Parameter

Parameter Description
min minimum value that the random integer can be
max maximum value that the random integer can be

Return

a random integer

Declaration

public static int randomWithRange(int min, int max) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**//w w  w. java  2 s . c  o m
     * Method for generating random integer between the 2 parameters, The order of
     * min and max do not matter.
     *
     * @param min minimum value that the random integer can be
     * @param max maximum value that the random integer can be
     * @return a random integer
     */
    public static int randomWithRange(int min, int max) {
        int range = Math.abs(max - min) + 1;
        return (int) (Math.random() * range) + (min <= max ? min : max);
    }

    /**
     * Method for generating random doubles between the 2 parameters, The order of
     * min and max do not matter.
     *
     * @param min minimum value that the random double can be
     * @param max maximum value that the random double can be
     * @return a random double
     */
    public static double randomWithRange(double min, double max) {
        double range = Math.abs(max - min) + 1;
        return (Math.random() * range) + (min <= max ? min : max);
    }

    /**
     * Method for generating random floats between the 2 parameters, The order of
     * min and max do not matter.
     *
     * @param min minimum value that the random float can be
     * @param max maximum value that the random float can be
     * @return a random float
     */
    public static float randomWithRange(float min, float max) {
        float range = Math.abs(max - min) + 1;
        return (float) (Math.random() * range) + (min <= max ? min : max);
    }
}

Related

  1. randomString(int size, String... keys)
  2. randomStringNumbers(int len)
  3. randomtest(int max)
  4. randomText(int length)
  5. randomWithinRange(int min, int max)
  6. randomWord(int wordLength)
  7. randomZeroString(int length)
  8. randowPartition(int[] array, int q, int p)
  9. randProductNumerid(final int c, final int count)