Generate a random Integer based on a min and max. - Android java.util

Android examples for java.util:Random Integer

Description

Generate a random Integer based on a min and max.

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    /**//  w  w  w  .ja v  a2  s  . c o  m
     * Generate a random Integer based on a min and max.
     * @param min ex. 1
     * @param max ex. 100
     * @return ex. a number between 1 and 100
     */
    public static int generateRandom(int min, int max) {

        Random randomGen = new Random();
        return randomGen.nextInt(max - min + 1) + min;
    }

    /**
     * Generate a random Integer based on a min and max.
     * @param seed the initial state, set this for better randomness
     * @param min ex. 1
     * @param max ex. 100
     * @return ex. a number between 1 and 100
     */
    public static int generateRandom(long seed, int min, int max) {

        Random randomGen = new Random(seed);
        return randomGen.nextInt(max - min + 1) + min;
    }

    /**
     * Generate a random Float based on a min and max.
     * @param min ex. 55.5
     * @param max ex. 100.9
     * @return ex. a number between 55.5 and 100.9
     */
    public static float generateRandom(float min, float max) {

        Random randomGen = new Random();
        return randomGen.nextFloat() * (max - min) + min;
    }

    /**
     * Generate a random Float based on a min and max.
     * @param seed the initial state, set this for better randomness
     * @param min ex. 55.5
     * @param max ex. 100.9
     * @return ex. a number between 55.5 and 100.9
     */
    public static float generateRandom(long seed, float min, float max) {

        Random randomGen = new Random(seed);
        return randomGen.nextFloat() * (max - min) + min;
    }

    /**
     * Generate a random Long based on a min and max.
     * @param min ex. 55876
     * @param max ex. 100329487
     * @return ex. a number between 55876 and 100329487
     */
    public static long generateRandom(long min, long max) {

        Random randomGen = new Random();
        return min + (long) (randomGen.nextDouble() * (max - min));
    }

    /**
     * Generate a random Long based on a min and max.
     * @param seed the initial state, set this for better randomness
     * @param min ex. 55876
     * @param max ex. 100329487
     * @return ex. a number between 55876 and 100329487
     */
    public static long generateRandom(long seed, long min, long max) {

        Random randomGen = new Random(seed);
        return min + (long) (randomGen.nextDouble() * (max - min));
    }
}

Related Tutorials