-5

So I needed to get random numbers between 25 and 75 and I tried two things:

System.out.println(random.nextInt(75)+25);
System.out.println((int)(Math.random()*75) + 25);

From what I understood, the "75" I wrote in both lines should be the greatest number I get and the "25" should be the smallest number. However, I got numbers like:

84,94,82,79,98 // these are only the numbers that went out of range

I guess I misunderstood the rules of nextInt and Math.random. How can I get the numbers I want(between 25 and 75)?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Alexis676
  • 15
  • 1
  • 75+25>75, use nextint(50) – MrTux Mar 16 '19 at 23:44
  • `random.nextInt(75)` represents range of values `[0, 75)` (75 is exclusive). When you add 25 minimal value becomes 0+25=25 and maximal value 75+25=100 which gives range `[25, 100)`. – Pshemo Mar 17 '19 at 00:12

2 Answers2

1

The range of your examples is 25 to 100 because you add twenty-five to the result. You wanted something like

System.out.println(random.nextInt(75 - 25) + 25);

because you want a value in the range 0 to 50 and then you shift that up twenty-five by adding twenty-five.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Max value returned from `random.nextInt(75)` is 74 final range is up to 99 *inclusive*, or 100 *exclusive*. – Pshemo Mar 17 '19 at 00:09
1

Think about this part:

random.nextInt(75) + 25

You're generating a number between 0 and 74, then adding 25. This generates a random number from 25 to 99. If it generates 74 and you add 25, it becomes 99.

You need to subtract the lower bound before generating:

random.nextInt(75 - 25) + 25)
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Thanks, this worked. But then I tried with smaller numbers `System.out.println(random.nextInt(1)+1);` and I got only the number "1" everytime. Shouldn't I be getting "2" as well? – Alexis676 Mar 17 '19 at 11:23
  • @Alexis676 Me and the other answer actually got a small detail wrong. The second number is actually exclusive. You need to add one to the upper bound. – Carcigenicate Mar 17 '19 at 14:01