-2

I tried to get a random number between 3 and 6 (inclusive):

public class A {              

 Random ran = new Random();                            
 public func1(){            
  x = 3 + ran.nextInt(7); // need Random number x from 3 to 6   
  y = 3 + ran.nextInt(7)             
 }
}    

but it often gives results 8 and 9! How it can be ?

I used

 x=(int) (3 + Math.random()*6);  

its give 8 sometimes too...
where is an Error???

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43

2 Answers2

0
3 + ran.nextInt(7); // need Random number x from 3 to 6   

ran.nextInt() will give you numbers between 0 (inclusive) and 7(exclusive). If you add 3, you'll end up with range 3 - 9.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
0

This is a good example of why you need write your own code and understand what you are writing.

   x = 3 + ran.nextInt(7);

If you read the javadoc for Random.nextInt(int) it says:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

So nextInt(7) is going to return a value between 0 (inclusive) and 7 (exclusive); i.e. 0 or 1 or 2 or 3 or 4 or 5 or 6.

That means that

   x = 3 + ran.nextInt(7);

gives you 3 or 4 or 5 or 6 or 7 or 8 or 9. That is what you are seeing.

The solution? How to generate a number in the range 3, 4, 5, 6?

Work it out for your self1. The exercise will do you good!


Lessons:

  1. Read the javadocs.
  2. Don't just copy code fragments. Copying code is not proper programming.

1 - SPOILER: x = 3 + ran.nextInt(4);

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216