Top community members

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - random int between MIN MAX value - both inclusive

2 points
Asked by:
Ticket Ninja
2338

How to generate random number in java between min and max value?
But I would like to create method to get number between min and max - both inclusive.
I don't like when I need to think if min or max is inclusive or exclusive :)
Let's say random number between 0 and 3:
[0, 3] - both inclusive (where 0 is min and 3 is max).

1 answers
1 points
Answered by:
Ticket Ninja
2338

Here we have Util class with small example if this method works as asked in questions. Both inclusive between 0 and 3.

[0, 3]

Code and output:

import java.util.Random;

public class RandomUtil {

    private static final Random RANDOM = new Random();

    public static int nextIntBetweenMinInclusiveMaxInclusive(int min, int max) {
        return RANDOM.nextInt((max - min) + 1) + min;
    }

    public static void main(String[] args) {

        for (int i = 0; i < 15; i++) {
            int randomNumber = nextIntBetweenMinInclusiveMaxInclusive(0, 3);
            System.out.println(randomNumber);
        }
    }
}

Output:

1
1
2
0
1
3
2
1
3
1
0
1
0
1
3

Like we can see, the method works, we get numbers between [0, 3] both inclusive.

0 comments Add comment

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more