0

Hello i'm trying to return array from my function but i got this in result:

[Ljava.lang.String;@1be6f5c3

but function output correctly, for example:

12, 54, 65
fun main() {
    val array = arrayOf(loopForNumbers(n))
    println(array)
}
fun loopForNumbers(n: Int): String {
    val array = IntArray(n)
    var i = 0
    while (i < n) {
        println("Input number № ${i + 1}")
        array[i] = readLine()?.toIntOrNull() ?: continue
        i++
    }
    println(array.joinToString())
    return array.joinToString()
}
1
  • All this is of course one more reason to prefer lists instead of arrays… Commented Feb 16, 2021 at 17:18

2 Answers 2

3

You got confused I think, it's better to return the array as-is and then format it

fun main() {
    val array = loopForNumbers(n)
    println(array.joinToString())
}

fun loopForNumbers(n: Int): IntArray {
    val array = IntArray(n)
    var i = 0
    while (i < n) {
        println("Введите число № ${i + 1}")
        array[i] = readLine()?.toIntOrNull() ?: continue
        i++
    }
    println(array.joinToString())
    return array
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thx, but in that way i got this: [I@1be6f5c3 but if correct it to fun main() { ` val array = arrayOf(loopForNumbers(n))` ` println(array.joinToString())` } fun loopForNumbers(n: Int): String { ` return array.joinToString()` } it works as it should
@ispite arrayOf() doesn't work this way, it's supposed to take a vararg parameter, meaning that it will create one element in the array for each parameter you pass. Here, you're passing a single parameter, so you're effectively creating an array of a single element, which is the string representation of the initial array. While this might print what you expect, it is conceptually quite different, and not usable in other pieces of the code. The code in this answer is much better, because it actually uses the actual array.
1

but function output correctly, for example:

12, 54, 65
val array = arrayOf(loopForNumbers(n))

This creates a single-element array containing (in this case) the string "12, 54, 65".

println(array)

println calls toString() on its argument, and for an array toString is pretty useless because it doesn't include the array contents; [Ljava.lang.String;@1be6f5c3 is a String array and [I@1be6f5c3 is an Int array, but the part after @ just lets you see if two arrays are the same. Instead try

println(array.joinToString())

see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to-string.html for documentation and optional parameters.

Comments

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.