Noccis
Noccis

Reputation: 83

How do I get the index var to work in my for loop?

It is now solved. Thank you all that hepled! :-)

I am new at programming and trying to learn. Wanted to write a code in Kotlin that creates a list with 10 spaces and then fills them with random numbers. But in my for loop the index value (myList[i]) is red. What am I doing wrong?

 var myList = listOf<Int>()
 val times = 10

    for (i in myList) {
        val randomNumber = (1..100).random()
        myList[i] = randomNumber
    }
}

The end code that works:

 var testar = mutableListOf<Int>()

    for (int in 0..10) {
        val randomNumber = (1..100).random()
        val int = randomNumber
        testar.add(int)
    }

Upvotes: 0

Views: 205

Answers (1)

Stachu
Stachu

Reputation: 1724

  1. myList should be mutable as you want to add items to it
  2. you need to iterate the 0..times not myList as it's empty
  3. you can only access particular index if it's not empty (so in case of myList after the numbers are added)

sample solution:

var myList = mutableListOf<Int>()
val times = 10

for (i in 0..times) {
    val randomNumber = (1..100).random()
    myList.add(randomNumber)
}
println("$myList")
println("${myList[0]}, ${myList[10]}")

Upvotes: 1

Related Questions