Skip to Content

Generate Random Int Within Given Range Example

Submitted By: Justin G.

  1. /*
  2.         Generate Random Int Within Given Range Example
  3.         This Java example shows how to generate an int randomly within given range
  4.         using Math class.
  5. */
  6.  
  7. public class GenerateRandomIntByRange {
  8.  
  9.         public static void main(String args[]){
  10.                
  11.                 /*
  12.                 The "(int)" parses the double to an int value replace 10 with
  13.                 your range of number.
  14.                
  15.                 If you want a number between 5 and 15 the range is 10 [15-5]
  16.                 replace the 5 with the staring number.
  17.                
  18.                 If you want the lowest number in the range to be 5 then add 5.
  19.                
  20.                 Example :
  21.                 int ran = (int)(Math.random()*100)-50;
  22.                 will return a value in the range [-50;50]
  23.                 */
  24.                
  25.                 int random = (int)(Math.random()* 10 ) + 5;
  26.                 System.out.println(random);
  27.         }
  28. }