How can I generate Java random integers?

I tried the following:
randomNum = minimum + (int)(Math.random() * maximum);.

But it didn’t work for me.

Java or Javascript?

It looks like you need help with Java, not JavaScript. I’ve moved this thread to the General Web Dev forum which is the best place for that.

1 Like

That should probably be:

randomNum = minimum + (int)(Math.random() * (maximum - minimum));

otherwise you risk overshooting the maximum.

1 Like

Then what is the best solution for this.

Okay, so since Math.random() will never return 1 we need to take that into account, otherwise we’ll never hit the actual maximum.

My final solution is:

int randomNum = minimum + (int)(Math.random() * (maximum - minimum + 1));
1 Like

The Java random integer generator is a type of pseudo-random number generator that generates integers in the range of 0 to 232 - 1. It can be used for cryptography and other applications where security is required.

The Java random integer generator is implemented as part of the standard library in the java.util.Random class, which provides a simple interface for generating unique integers on demand. This class supports both ints and longs but does not provide any means to generate floating point numbers.

To generate a random long, you must use System.nanoTime() to get an estimate of the current time and then use that value as an argument to SecureRandom’s nextInt method somewhere after System.currentTimeMillis() has been called at some point during your program execution

What? That’s a very odd range, and the only random generator I know in Java returns a number between 0 (inclusive) and 1 (exclusive), as demonstrated in the posts above…

1 Like

This could help me.
Thanks

Method: Using Math.random
For generating random numbers within a range using Math.random() , follow the steps below:

  1. Declare the minimum value of the range
  2. Declare the maximum value of the range
  3. Use the formula Math.floor(Math.random()*(max-min+1)+min) to generate values with the min and the max value inclusive.
class GenerateRandom {
    public static void main( String args[] ) {
      int min = 50;
      int max = 100;
        
      //Generate random int value from 50 to 100 
      System.out.println("Random value in int from "+min+" to "+max+ ":");
      int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
      System.out.println(random_int);
    }
}

This method can only be used if you need an integer or float random value.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.