Random nextInt(int) in Java

nextInt(int): This method is available in java.util.Random class of Java.

Syntax:

int java.util.Random.nextInt(int bound)

This method takes one argument. This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

Parameters: One parameter is required for this method.

bound: the upper bound (exclusive). Must be positive.

Returns: the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive)from this random number generator's sequence.

Throws:

IllegalArgumentException - if bound is not positive.

Approach 1: When no exception

Java

import java.util.Random;

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

        Random random = new Random();

        int bound = 10;

        System.out.println(random.nextInt(bound));
    }
}

Output:

0


Approach 2: IllegalArgumentException 

Java

import java.util.Random;

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

        Random random = new Random();

        int bound = -10;

        System.out.println(random.nextInt(bound));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.base/java.util.Random.nextInt(Random.java:388)


No comments:

Post a Comment