Adding Value an Empty Array

Hi Everyone,

I’m just a beginner in Kotlin. My question maybe seems stupdi but i need some help. I define an empty array and i need to add some values to array in a loop. My code is below.

fun main(args: Array<String>) {

print("Enter a Word")

var word : String = readLine()!!
var letters = emptyArray<Char>()

for (i in 0..word.length - 1) {
    
    var OneLetter: Char = word[i].toChar()

    var number : Int = -1
    letters[number++] = OneLetter
}

print(letters) }

emptyArray returns a zero length array. What you want is a CharArray(size).
And this will also fail “letters[number++]” because the post-increment operator will, as the name says, increment the value after returning it. So in the first iteration number will be -1.

1 Like

should i cgange the code as letters[++number] = OneLetter ? And also CharArray(Size) bu i don’t know the size, can be input a random word.

Kotlin like java has fixed size array, you can’t increase its size once it is created. You should use MutableList instead.

1 Like

there’s another problem. You declare numbers inside of the for loop. So you will only ever set the first value of the array. The rest will stay empty.

1 Like

Thanks Everyone,

I solved like this:

fun main(args: Array<String>) {

print("Enter a Word")

var word : String = readLine()!!
var letters : MutableList<Char> = mutableListOf<Char>()

for (i in 0..word.length - 1) {

    var OneLetter: Char = word[i].toChar()

    letters.add(OneLetter)

}
print(letters)

}

Nice. Instead of 0..word.length - 1 you can use 0 until word.length. It does the same but looks a bit nicer :wink:

1 Like

You can use

fun main() {
  val word : String = readLine()!!
  val letters = Array(word.length) { word[it] }
  print(letters)
}
2 Likes
fun main() {
  readLine()?.let{ word ->
    print(Array(word.length) { word[it] })
  } ?: error("oops!")
}

:wine_glass:

1 Like