Home > Mobile >  How to create a dynamic 2 dimensional array in Kotlin?
How to create a dynamic 2 dimensional array in Kotlin?

Time:09-28

My question is how to create a Dynamic 2D array in Kotlin. so that the user can input values when running the program. I have tried it with default values to add 2 matrices. but I need the program with a dynamic array and I NEED TO INPUT VALUES TO ARRAY EACH TIME WHEN I AM RUNNING THE PROGRAM. please help me to convert my code.

Below is my code.

fun main(args: Array<String>) {
    var rows = 2
    var columns = 2
    var firstMatrix = arrayOf(intArrayOf(5,8), intArrayOf(3,8))
    var secondMatrix = arrayOf(intArrayOf(3,8), intArrayOf(8,9))
    // Adding Two matrices
    var sum = Array(rows) { IntArray(columns) }
    for (i in 0..rows - 1) {
        for (j in 0..columns - 1) {
            sum[i][j] = firstMatrix[i][j]   secondMatrix[i][j]
           // println(sum[i][j])
        }
    }
    /// Displaying the result
    println("Sum of two matrices is: ")
    for (row in sum) {
        for (column in row) {
            print("$column    ")
        }
        println()
    }
}

CodePudding user response:

You can use Kotlin's readln function to read user input from console. It gives you a string, which you can split with spaces to get all the numbers in one row which can then be mapped to Int from String.

val rows = 2
val columns = 2
println("Enter elements of first array:")
val firstMatrix = (1..rows).map {
    readln().split(' ').map { it.toInt() }
}
println("Enter elements of second array:")
val secondMatrix = (1..rows).map {
    readln().split(' ').map { it.toInt() }
}

After this you can use your existing code to find the sum matrix.

Sample execution:

Enter elements of first array:
1 2
3 4
Enter elements of second array:
3 5
2 5
Sum of two matrices is: 
4    7    
5    9
  • Related