Java Algorithms How to - Generate Random numbers in a range


We would like to know how to generate Random numbers in a range.


import java.util.Random;
// ww w.j a  v a2s.c  o m
public class Main {
  public static void main(String[] args) {
    int randomNumberBetween1To100 = getRandom(0, 100);
    System.out.println("Random number between 1 to 100 is: "
        + randomNumberBetween1To100);

  public static int getRandom(int minNumber, int maxNumber) {
    Random rand = new Random();
    int randomNum = rand.nextInt(maxNumber - minNumber);
    return randomNum;

The code above generates the following result.