1

I have created a 2D array named squareData as shown below:

 private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?

2 Answers 2

2

You can iterate in the array like this :

for (strings in squareData) {
    for (string in strings) {
        Your code here
    }
}

The first for iterate through the first dimension so it has string arrays and the second one through the second dimension so it has the string values

Sign up to request clarification or add additional context in comments.

Comments

2

You can use regular nested for loop.

for (arr in squareData) {
    for (s in arr) {
        println(s)
    }
}

You can iterate using forEach:

squareData.forEach { it.forEach(::println) }

or if you want index position as well, forEachIndexed:

squareData.forEachIndexed { i,it -> println(i); it.forEach(::println) } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.