Caffeinated
Caffeinated

Reputation: 12484

Why are they adding 1 to the RandomInt Integer here?

I'm studying code from Horstmann's java book:

Integer key = new Random().nextInt(elements.length) + 1;

What puzzles me is the +1 part , is there any reason for this, or just for more "randomness"? Thanks alot!

Upvotes: 1

Views: 78

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158599

is there any reason for this, or just for more "randomness"?

No this does not add "randomness", 1 is clearly not random, this is to shift the range from [0,elements.length-1] to [1,elements.length].

Upvotes: 2

jh314
jh314

Reputation: 27812

I think the +1 is to shift the domain of random integers, from

[0,elements.length-1]

to

[1, elements.length]

Horstmann simply wants a random integer from 1 to elements.length for his key.

Upvotes: 3

SLaks
SLaks

Reputation: 887857

nextInt() returns a number more than or equal to zero and less than its parameter.

+ 1 shifts that range.

Upvotes: 4

Related Questions