Generate random Int within a range - Android java.lang

Android examples for java.lang:Integer

Description

Generate random Int within a range

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }//from w  w w.j a v a2  s . c  o  m
}

Related Tutorials