Nourdine Dali
Nourdine Dali

Reputation: 41

Why to add 0 while using nextInt()

I am following an instructor creating tic tac toy game, to make it autoplay.

var r = Random()
val randInt = r.nextInt(emptyCell.size-0) + 0    // adding 0 here

why do we need to add +0 here?

Upvotes: 2

Views: 220

Answers (3)

Willi Mentzel
Willi Mentzel

Reputation: 29864

Adding 0 will work but it does not change anything.

Note that you are using Java's java.util.Random which would limit your code to the JVM.

If you use kotlin.random.Random your code will target all platforms that Kotlin does and would be simpler because you don't need to instantiate a class.

You can use it like this:

val randInt = Random.nextInt(emptyCell.size)

Check out the other variants of nextInt if you don't need to specify bonds or you need to specify an upper bound.

Upvotes: 0

Andy Jazz
Andy Jazz

Reputation: 58503

It's a billet for changing a value if you wish to. Author just showed you where and how to put it to.

Here's how your code should look like:

var random = Random()
var randomIndex: Int?
randomIndex = random.nextInt(emptyCell.size - 1) + 2   // two values instead of 00
println("randomIndex $randomIndex")

val emptyCellId = emptyCell[randomIndex]
println("emptyCellId $emptyCellId")

var btnSelect: Button?
btnSelect = setButtonId(noOfCards, emptyCellId)

Upvotes: 1

zsmb13
zsmb13

Reputation: 89608

There's no reason why you'd have to write down + 0 in that case. nextInt returns an Int, so adding 0 as an Int to it does absolutely nothing - doesn't change the type or affect the value - as you'd expect.

Probably a typo in the tutorial.

Upvotes: 1

Related Questions