0

I created an arraylist with 4 items

val myList = arrayListOf("Item1", "Item2", "Item3", "Item4")

Then I printed a random item from myList

val randomNum = Random()
val randomItem = randomNum.nextInt(myList.count())
println(myList[randomItem])

Shouldn't this fail? Once randomItem is equal to 4? Ideally what I'm asking is that randomItem is returning an int from 0-4, correct? But the arraylist index is only 0-3. Should I do -1 to randomItem? I'm just confused because the program isn't throwing an error.

1
  • Don't be sorry. You learn. But next times, think of javadoc. It contains most important things. Commented Mar 17, 2018 at 11:08

2 Answers 2

4

See the API here Random.nextInt(int bound)

public int nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.

Parameters: bound - the upper bound (exclusive). Must be positive.

Returns: the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence

So in your case, you get 0, 1, 2 or 3

Sign up to request clarification or add additional context in comments.

1 Comment

my apologies, i'm obviously not thinking today
1

The documentation explains it pretty well:

int nextInt(int bound)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.