0

I am very new to Java and I am stuck on this, I am using the formula:

min + (int)(Math.random()*(max-min+1))

and I have to write statements that assign random integers to the variable x in the following ranges

  1. 1 < x <= 8
    1 being min and 8 being max

    Am I correct that it would be 1 + (int)(Math.random()*(8-1+1))?

  2. -5 < x <= 3
    3 being min and -5 being max

    and this would be 3 + (int)(Math.radom()*(-5-3+1))?

Any help would be greatly appreciated.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
joe8032
  • 11
  • 1
  • 4

4 Answers4

3

You want a formula to take a real number in the range [0..1), and return an integer in the range [1..8].

  • When random() picks a real number it the range [0..1),
  • and you multiply it by 8,
  • you get a value in the range [0.0 .. 8.0).
  • Then you then convert to (int), you have an integer in the range [0 .. 7],
  • because conversion to (int) rounds using the 'floor' step function.
  • Add one.
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42
0

use following code. It will generate nos between 0 and max value supplied.

 Random generator = new Random(); //Creates a new random number generator
  for(int i=0; i<100; i++){
      /**
       *Returns a pseudorandom, uniformly distributed int value
       * between 0 (inclusive) and the specified value (exclusive), drawn from
       * this random number generator's sequence
       */
        System.out.println(generator.nextInt(100));
  }
Shamse Alam
  • 1,285
  • 10
  • 21
0
  1. Get random value with range ( min, max ] , this is the same with the question.

If JDK 1.7 version is used, then you can use one line code to implement such function:

ThreadLocalRandom.current().nextInt(min, max)+1

If JDK version is under 1.7, we can implement it using the following way.

Random random = new Random();

random.nextInt(max - min) + min +1;

2.Get random value with range [ min, max )

Use, ThreadLocalRandom.current().nextInt(min, max)

or

random.nextInt(max - min) + min ;

Mengjun
  • 3,159
  • 1
  • 15
  • 21
0

Math.random() gives you between 0 and 1. Multiply this by your range, the size of the range, not the absolute value. If you want 1-10 that's 9, if you want 0-10 that's 10, if you want 5-7 that's 2, etc.

Then add or subtract to go from 0 to the starting value.

If you want 0-9 then you're done (you should have multiplied by 9 in the previous step)

If you want 1-10 then add 1

If you want -5 to 5 then subtract 5

If you want 5-7 then do (Math.random()*2)+5;

SpacePrez
  • 1,086
  • 7
  • 15