[java] Java Generate Random Number Between Two Given Values

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)?

This question is related to java random numbers

The answer is


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.


Like this,

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

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*/

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." );
        }                     
    }
}

Use Random.nextInt(int).

In your case it would look something like this:

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

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;

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python