Adding Value an Empty Array


#1

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) }

#2

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.


#3

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.


#4

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


#5

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.


#6

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)

}


#7

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


#8

You can use

fun main() {
  val word : String = readLine()!!
  val letters = Array(word.length) { word[it] }
  print(letters)
}

#9
fun main() {
  readLine()?.let{ word ->
    print(Array(word.length) { word[it] })
  } ?: error("oops!")
}

:wine_glass: