Q:

Java program to generate random numbers between given ranges

belongs to collection: Java Basic Programs

0

Given ranges of the numbers and we have to generate and print the random number using java program.

    Input:
    Enter starting range: 5
    Enter final range: 50

    Output:
    Random number between given range: 18

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to generate and print random number in Java

import java.util.Scanner;

public class GenerateRandomIntegers
{
	public static void main( String args[] )
	{ 
		// create object here.
		Scanner sc = new Scanner( System.in ); 

		// enter the range between which we have to print random numbers.
		System.out.print("Enter starting range : "); 

		int rsnum = sc.nextInt(); 

		System.out.print("Enter final range : "); 

		int renum = sc.nextInt(); 

		int random_num = rsnum + (int)(Math.random() * ((renum - rsnum) + 1));
		System.out.println("Random number between given range : " +random_num);
	}  
}

Output

First run:
Enter starting range : 5
Enter final range : 50
Random number between given range : 18

Second run:
Enter starting range : 1
Enter final range : 10
Random number between given range : 5

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check whether a given number is ug... >>
<< Java program to find perimeter of a rectangle...