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