
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Possibilities of Duplication for Random Number 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
Advertisements