×

Java Programs

Java Practice

Java program to generate random numbers from 0 to given range

Generate Random Numbers in Java - This program will read an integer as a maximum range, and print 10 random numbers from 0 to maximum Range.

In this program we will use Random class to generate random numbers by passing maximum range, to use Random class we use java.util.Random package.

Generate Random Numbers using Java program

//Java program to generate random numbers
//from 0 to given range.

import java.util.Scanner;
import java.util.Random;

class RandomNumber {
  public static void main(String[] args) {
    int maxRange;

    Scanner SC = new Scanner(System.in);
    //instance of Random class
    Random rand = new Random();

    System.out.print("Enter maximum range: ");
    maxRange = SC.nextInt();

    //generate 10 random numbers from 0 to maxRange
    for (int loop = 1; loop <= 10; loop++) {
      System.out.println(rand.nextInt(maxRange));
    }
  }
}

Output

    Enter maximum range: 50
    6
    19
    31
    10
    13
    9
    4
    47
    4
    19

Core Java Example Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.