简体   繁体   中英

random number with range and multiplier in java

I'm trying to generate a random number within a range, and of a specific multiple. My example would be within the range of 60 - 500, and only multiples of 5, eg 60, 65, 70 -> 500

I'm trying to use random.nextInt(), but I can either get the range to work, or the multiplier, but not both.

Any assistance would be greatly appreciated!

I'd work my way backwards - generate a random number and then multiply it by the multiple you want:

int multiple = 5;
int rangeStart = 60;
int rangeEnd = 500;

int calcRangeStart = rangeStart / multiple;
int calcRangeEnd = rangeEnd / multiple;

int random = new Random().nextInt(calcRangeStart, calcRangeEnd) * multiple;

First work out the number of possible values for your random number, which is

((500-60)/5 + 1) or
((505-60)/5)

using integer division. Using this value as an argument to Random.nextInt will give you values starting from 0. So you just need to multiply by 5 and add 60 to get values in your desired range

Random random = new Random();
(random.nextInt((505-60)/5) * 5 + 60)

You can define your from-to and multiply numbers as ints and then generate them like this:

int from = 60, to = 500, multi = 5;
Random rand = new Random();
int n = multi*(Math.round(rand.nextInt((to+multi-from))+from)/multi);

This code will generate numbers from 60 to 500 in multiplies of 5 only.

int seed = 5;
Random random = new Random();
int inf = 12;
int sup = 100;
int number = random.nextInt((sup-inf)+1) + inf;
number *= seed;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM