Home » Java programs » Java basic programs

Java program to generate random numbers between given ranges

Here, we are implementing a java program that will generate and print random numbers between given ranges?
Submitted by IncludeHelp, on January 02, 2018

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

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.