Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Internet

How to generate a random number from 0 to N in Java

See also

Here are the steps to generate a random number from 0 to N in Java. If you do not want to include zero, then simply add one to the result.

Step 1 - Import the Java Random class.

import java.util.Random;

Step 2 - Create an instance of the Random class.

Random rand = new Random();

Step 3 - Call the nextInt() method.

This nextInt() method accepts an integer parameter. It generates a random number from 0 to that number, but not including that number. For example, this statement generates a random number from 0 to 9:

int num = rand.nextInt(10);

Here is a sample program that prints 100 random numbers from 0 to 9:

import java.util.Random;

public class Test {
public static void main(String[] args) {

Random rand = new Random();
for (int i=0; i < 100; i++) {
int n = rand.nextInt(10);
System.out.println(n);
}

}
}

For more articles, please subscribe, add or follow me here.

Advertisement

Don't Miss

  • Crew
    'The Crew' preview: Ubisoft has on its hands the 'Destiny' of racing games
    Games Preview
  • Cell phone
    A bill legalizing unlocking phones has passed Congress and is expected to be signed into law
    Video
    Tech Buzz
  • Crew
    'The Crew' exclusive: Details on in-game servers, leveling up and online play
    Games Interview
  • Comic Con
    See 10 defining moments from the 2014 San Diego Comic-Con
    Camera
    10 Photos
  • Unity Exclusive
    'Assassin's Creed Unity' exclusive: Tell the world, 'I'm coming home'
    Camera
    Games Interview
  • Typing
    Is your brokerage account safe from the attacks of cyber thieves?
    Video
    Headlines