- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to calculate the possibilities of duplication for random number within a range in Java
To get the duplicate numbers for random numbers in a range, loop through and create two Random class objects −
Use nextInt() to get the next number −
intrandVal1 = new Random().nextInt(50); intrandVal2 = new Random().nextInt(50);
Now, compare both the above numbers −
if (randVal1 == randVal2) { System.out.println("Duplicate number = "+randVal1); }
All the above is to be done in a loop −
for (int i = 1; i <= 50; i++) { intrandVal1 = new Random().nextInt(50); intrandVal2 = new Random().nextInt(50); if (randVal1 == randVal2) { System.out.println("Duplicate number = "+randVal1); } }
Example
import java.util.Random; public class Demo { public static void main(String[] args) { for (int i = 1; i<= 50; i++) { int randVal1 = new Random().nextInt(50); int randVal2 = new Random().nextInt(50); if (randVal1 == randVal2) { System.out.println("Duplicate number = "+randVal1); } } } }
Output
Duplicate number = 35 Duplicate number = 28
- Related Articles
- Java Program to create random BigInteger within a given range
- Java Program to generate random number array within a range and get min and max value
- Java program to generate random numbers within a given range and store in a list
- Armstrong number within a range in JavaScript
- How to create a random number between a range JavaScript
- How to create a random vector for a range of values in R?
- Python Generate random numbers within a given range and store in a list
- Python program to generate random numbers within a given range and store in a list?
- Constrain a number within a given range in Arduino
- Generating random number in a range in C
- How to get the total number of leap days in the years within range in Python?
- How can I generate random number in a given range in Android?
- How to sort a random number array in java?
- Python - Find the number of prime numbers within a given range of numbers
- Finding the count of numbers divisible by a number within a range using JavaScript

Advertisements