0

Could someone help me to understand where I've gone wrong because it seems that I keep on getting this error:

java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

fun main()
{

    arrayOfNulls<String?>(size = 11)
    var firstWord : String?

    print("Enter in the sentence ")
    var strAnagram : String = readLine()!!

    var arrUserInput = strAnagram.split(" ")
    var  arrFirstLetter = charArrayOf()

    for(x in 0..arrUserInput.size+1)
    {
        firstWord = arrUserInput.get(x)
        arrFirstLetter[x] = firstWord[0]

    }

    for (y in 0..11)
    {
    println(arrFirstLetter[y])
    }

}
1
  • 2
    It looks like you're trying to make acronyms, not anagrams. Commented Apr 27, 2020 at 14:18

1 Answer 1

3

When you write var arrFirstLetter = charArrayOf() you are creating an empty array.

Then when you write arrFirstLetter[x] = firstWord[0], you are trying to assign to the element at index x of an empty array. Because the array is empty, this is generating ArrayIndexOutOfBoundsException.

In general it's better to avoid trying to loop over collections by using their index and instead use a for loop or the map extension function.

You can print out the first letters of each word like this:

fun main() {
    print("Enter in the sentence ")
    val userInputWords: List<String> = readLine()?.split(" ") ?: emptyList()

    for (word in userInputWords) {
        println("First letter: ${word[0]}")
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I missed the case where the input contains an empty string. It's more complex, but you can cover that with for (word in userInputWords.filter { it.isNotEmpty() })

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.