This question already has an answer here:
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)?
if You need to generate more than one value, then just use for loop for that
If You want to specify a more decent range, like from 10 to 100 ( both are in the range )
so the code would be :
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:
}
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.
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:
Like this,
Use Random.nextInt(int).
In your case it would look something like this:
One can also try below: