How to get a random number in Java

Hi guys! In this tutorial I will explain how you can use the random class in Java.

To get a random number in Java, you must write only this code:

Random rand = new Random();
int i = rand.nextInt(100);
out.print(i);

This code will get a random number between 0 and 100. If you change 100 to 1000, rand.nextInt(1000), it will display a random number between 0 and 100.

Now I will write a sample code, where II can enter a number and this code will display a random number between 0 and inserted number:

import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in)
);
out.print("Enter a number:");
int get;
get = Integer.parseInt(in.readLine());
Random rand = new Random();
int i = rand.nextInt(get);
out.print(i);
}

}

Video tutorial:









Leave a Comment