chevron_left
358 points
19 13 11

In the programming world, especially while developing some games, we need to generate random numbers. For example, in Ludo (the world-famous dice game) or the cards game, random numbers are generated each time a player rolls the dice. So, it is good to know the logic behind the random numbers. In this article, we are going to see how to generate random numbers with or without range in Java.

Generating Random Numbers:


Java provides different ways to generate random numbers such as Random class, Math.random() method, or ThreadLocalRandom class. In this post, we will be using the Random class to generate the random numbers. Here is the code that generates 5 random numbers without any range:
(Please refer to the comments to understand code)
import java.util.*;      //you can replace this line with import java.util.Random;
public class Main
{
public static void main(String[] args) 
{
Random random = new Random();   //creating instance of Random class
for(int i =0; i<5; i++)    //loop to generate 5 numbers
{
    int numbers = random.nextInt();   //variable to store random numbers
    System.out.println("Random number: " + numbers);   //printing the random number 
}
}
}

Output:

Random number: -1075417638
Random number: -1101527741
Random number: -585686184
Random number: -114559821
Random number: 658556963

Generating Random Numbers Within a Range:

To generate a random number within a range, we only need to pass the upper bound as an argument to the nextInt() method. Here is the code that generates 5 random numbers within a given range:
(Please refer to the comments to understand code)

import java.util.*;      //you can replace this line with import java.util.Random;
public class Main
{
public static void main(String[] args) 
{
Random random = new Random();   //creating instance of Random class
for(int i =0; i<5; i++)    //loop to generate 5 numbers
{
int numbers = random.nextInt(10);   //variable to store random numbers
System.out.println("Random number: " + numbers);   //printing the random number 
}
}
}

Output:

Random number: 0
Random number: 3
Random number: 7
Random number: 8
Random number: 7

I hope you find this post helpful.

More Posts

How to get a random number between 1 and 10 in java. Huzaifa-Glitch - May 22
Java random number between 1 and 11 amna - Oct 18, 2020
Java random number between 1 and 100 Hasnain_khan - Oct 9, 2020
Java generate a random number between 1 and 10 offonime - Jul 14
How to Generate Random Number in Java muliemes - May 17
Generate a random number between 1 and 10 in JAVA MallikaShaik672 - Oct 17, 2020
choose a random number in java SharadMagar450 - Aug 7
Generate random number in php without repetition ahsanhanif99 - Aug 8
Generate random numbers between 1 and 10 in C++ Lalit Kumar - May 12, 2020
How to generate random numbers in c++ between 0 and 100 Sanjana Sagar - May 19