- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Random number generator in Java
To generate random numbers in Java, use.
import java.util.Random;
Now, take Random class and create an object.
Random num = new Random();
Now, in a loop, use the nextInt() method since it is used to get the next random integer value. You can also set a range, like for 0 to 20, write it as.
nextInt( 20 );
Let us see the complete example wherein the range is 1 to 10.
Example
import java.util.Random; public class Demo { public static void main( String args[] ) { Random num = new Random(); int res; for ( int i = 1; i <= 5; i++ ) { res = 1 + num.nextInt( 10 ); System.out.printf( "%d ", res ); } } }
Output
4 5 9 6 9
Advertisements