Why to add 0 while using nextInt()

2019-07-11 02:35发布

问题:

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?

回答1:

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.



回答2:

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)


回答3:

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.



标签: random kotlin