This site requires JavaScript, please enable it in your browser!
Greenfoot back
ari21
ari21 wrote ...

2017/12/6

Randomly pick specific number

ari21 ari21

2017/12/6

#
So let's say I got 2 numbers, 65 and 75, is there any way so Greenfoot only pick between 65 or 75? Thanks!
Yehuda Yehuda

2017/12/7

#
You randomly choose the amount of numbers you want to be picked from, then add the lowest number in your range.
Greenfoot.getRandomNumber(10) + 65;
danpost danpost

2017/12/7

#
int choice = Greenfoot.getRandomNumber(2)*10+65
ari21 ari21

2017/12/7

#
Thanks for the help! ^^
danpost danpost

2017/12/7

#
More generally, you could have something like this:
int[] nums = new int[] { 65, 75 }; // any set of values
int choice = nums[Greenfoot.getRandomNumber(nums.length)];
ari21 ari21

2017/12/7

#
Never thought of using an array. Thanks! ^^
Yehuda Yehuda

2017/12/8

#
But, if you use an array and you want a random number chosen with the range of 65 to 75, then you will need to set each int variable that's part of the array to each of the numbers you want chosen from.
int[] nums = new int[] {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75};
It can be done with a loop but you still need an initialization for each number you want to be able to choose from (instead of getting one variable which is randomly initialized with a number in your range).
ari21 ari21

4 days ago

#
sorry if I confuse you, but what I wanted actually is Greenfoot randomly pick from set of my own specific number (in this case, what I wanted is to pick only 65 or 75 and not any number between that) and in this case danpost's code fulfills what I needed ^.^ once again, thanks for the help!
Yehuda Yehuda

3 days ago

#
I think the word "between" in your first post mixed me up.
danpost danpost

3 days ago

#
Yehuda wrote...
I think the word "between" in your first post mixed me up.
What clued me in was "between 65 or 75" -- not and.
You need to login to post a reply.