Create Random integer within a range in Java

Description

The following code shows how to create Random integer within a range.

Example


/*  w w  w .j a  v a  2s  .c  om*/
public class Main {
  public static void main(String[] args) {
    int roll;
    String msg = "Here are 100 random rolls of the dice:";
    System.out.println(msg);
    for (int i = 0; i < 100; i++) {
      roll = randomInt(1, 6);
      System.out.print(roll + " ");
    }
  }

  public static int randomInt(int low, int high) {
    int result = (int) (Math.random() * (high - low + 1)) + low;
    return result;
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization