Out of bound error in function

Hello eveyone

I am a beginner at kotlin
I am working on the following function

fun wordSelector(): Triple<String, List<String>, ArrayList<Int>> {

    blanks.clear()                                    
    randomindex.clear()                               


    val size = words.size                            
    val randomise = (0 until size).random()    
    selectWord = words.elementAt(randomise)           
    val blankSize = selectWord.length-1              

    for (i in 0..blankSize){
        checkArray[i] = selectWord[i].toString()
    }

    for (i in 0..blankSize) blanks.add("_")     


    for (i in 0..blankSize) {

        val randomBlank = (0..blankSize-3).random()   
        if (randomindex.contains(randomBlank)) {      
            continue
        }
        else {
            randomindex.add(randomBlank)           
        }

    }

    return Triple(selectWord, blanks, randomindex)  
}

I am encountering the following error :

Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)

I’m getting this error at the following line of the code:

 for (i in 0..blankSize){
        checkArray[i] = selectWord[i].toString()
    }

I am getting this out of bound error even when the size in for loop is -1 the actual size. (i.e blankSize = selectWord.length - 1)
Any solution?

Thank you

Suganesh

What about checkArray? Are you sure it’s at least blankSize in lenght?
You haven’t shown it definition and you’re not resizing it beore writing to it.

I have defined it in the main function which is in a different file. I am working on a hangman game, and its a package, the above-mentioned function is in a separate file within the package.

Can you give an example of what do you mean by resizing ?

Thank you !

Make sure that checkArray[i] is a valid expression. If checkArray doesn’t have enough elements that will throw the exception you saw.
I don’t know checkArray type. If it’s an array you need to allocate a new one. If it’s an initially empty list you can just do checkArray.add(selectWord[i].toString()). If it’s a list with something in it you might want to clear it beforehand.

In genernal this isn’t very idiomatic kotlin one would usually do checkArray = selectWord.map{ it.toString() }

1 Like

checkArray is a valid expression. Anyway checkArray.add(selectWord[i].toString()) this did the job.
I wanted to add the elements from selectWord to checkArray in same order as selectWord. e.g if selectWord has the word cold then I wanted checkArray to have it as “c”,“o”,“l”,“d”.
But seems like order does not matter. It works

Thank you !