230

I would like to know how to generate a random number between two given values.

I am able to generate a random number with the following:

Random r = new Random();

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        a[i][j] = r.nextInt();
    }

}

However, how can I generate a random number between 0 and 100 (inclusive)?

0

7 Answers 7

552

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you - I have tried that but it does not seem to work. I am using the random numbers from 0 to 100 (inclusive) to populate a multidimensional array; when trying this it populates the array with extremely large and extremely small numbers. For example, -3.76556749E8 3.0207573E8 2.033182079E9 -6.86227134E8.
Could you post how you invoke r.nextInt() and with which values?
@Thomas Random r = new Random(); System.out.println(r.nextInt(High - Low) + Low);
With respect to the Java naming convention the variable names should start with lower case character
in this Result range is 10 to 100 ,r.nextInt(High-Low) given range is 0 to 90
|
68

Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:

int r = (int) (Math.random() * (upper - lower)) + lower;

2 Comments

This is exclusive to upper
int r = (Math.random() * (upper - lower)) + lower; It would be inclusive for lower. It might be helpful.
19
int Random = (int)(Math.random()*100);

if You need to generate more than one value, then just use for loop for that

 for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*100);
        System.out.println(Random);
       }

If You want to specify a more decent range, like from 10 to 100 ( both are in the range )

so the code would be :

   int Random =10 +  (int)(Math.random()*(91));
   /* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
  *Where min is the smallest value You want to be the smallest number possible to       
  generate and Max is the biggest possible number to generate*/

3 Comments

Maybe a little late, and it's always bound to opinions and code styles, but usually you don't create a variable with an uppercase, so it's "better" to name it "random" instead of "Random". Classes are usually with uppercase :)
This will fail in case where max is Integer.MAX_VALUE and min is 0. Use Math.round instead of casting to int to solve that.
With respect to the Java naming convention the variable names should start with lower case character
9

Like this,

Random random = new Random();
int randomNumber = random.nextInt(upperBound - lowerBound) + lowerBound;

Comments

2

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Comments

2

Java doesn't have a Random generator between two values in the same way that Python does. It actually only takes one value in to generate the Random. What you need to do, then, is add ONE CERTAIN NUMBER to the number generated, which will cause the number to be within a range. For instance:

package RandGen;

import java.util.Random;

public class RandGen {


    public static Random numGen =new Random();

public static int RandNum(){
    int rand = Math.abs((100)+numGen.nextInt(100));

    return rand;
}

public static void main(String[]Args){
   System.out.println(RandNum());
}

}

This program's function lies entirely in line 6 (The one beginning with "int rand...". Note that Math.abs() simply converts the number to absolute value, and it's declared as an int, that's not really important. The first (100) is the number I am ADDING to the random one. This means that the new output number will be the random number + 100. numGen.nextInt() is the value of the random number itself, and because I put (100) in its parentheses, it is any number between 1 and 100. So when I add 100, it becomes a number between 101 and 200. You aren't actually GENERATING a number between 100 and 200, you are adding to the one between 1 and 100.

Comments

1

One can also try below:

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

        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        double Random;

        if (n1 != n2)
        {
            if (n1 > n2)
            {
                Random = n2 + (Math.random() * (n1 - n2));
                System.out.println("Your random number is: " + Random);
            }
            else
            {
                Random = n1 + (Math.random() * (n2 - n1));   
                System.out.println("Your random number is: " +Random);
            }
        } else {
            System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
        }                     
    }
}

2 Comments

Bit verbose and clumsy. You shouldn't need to repeat that code, just to decide whether to have n1 or n2's value first.
With respect to the Java naming convention the variable names should start with lower case character

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.