programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# random

Hobi Kod
Greenhorn
Posts: 7
how to choose number of random interval ? i try but It is not working.
i have a mak and min number

what is my fault ?

Hobi Kod
Greenhorn
Posts: 7
how to choose number of random interval ? i try but It is not working.
i have a mak and min number

what is my fault ?

i choose 12 and 15 my programe choose 20

Hobi Kod
Greenhorn
Posts: 7

Winston Gutkowski
Bartender
Posts: 10575
66

PatienceIsAVirtue. We're all volunteers on here, so please don't badger. It's more likely to delay responses than speed them up.

You also haven't shown us any code, so we have no more idea what your problem is than you do.

Winston

Piet Souris
Master Rancher
Posts: 2044
75
Easy, International Rescue has just been informed... thunderbirds are go (yes, I'm that old)

Look at your formula, and assume that 'maks' means 'mak'. Let x = Math.random() × mak
then 0 <= x < mak

and therefore min <= x +  min < mak + min

So, taking the Int of the middle term, we get that

min <= int <= mak + min - 1

And so, with min = 12 and mak = 15, 20 is a perfect outcome!

If you want outcomes between min and max, you must limit the possible range of x (see beginning of my reply). Do you see how that can be done?

Campbell Ritchie
Marshal
Posts: 56592
172
I would suggest that (despite what the Java™ Tutorials say), you shou‍ld only use Math#random when you want a double in the range 0.0...0.99999999999999...
When you try to convert that to an int, you are actually going back on yourself. Math#random uses a Random object and that uses its nextInt method to calculate a double. Now you are taking that double and converting it back to an int. But the double was made from an int. Also, the placement of () in the formula used is very error‑prone.
I suggest you use a Random object:-Now, go back to the Random link I showed you and find the nextInt method. Look very carefully at its parameters (there shou‍ld be one int; don't use the no‑arguments version). Now you can work out what i and j in the code I showed you shou‍ld be.