Monday, February 12, 2018

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


Answer



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)


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...