Need Assistance in find Min And Max from user input Array in Kotlin

On the Android Studio emulator The user is required to enter a maximum of 10 numbers. When I put in the number 1 the output shows 0 instead of 1 (this is for the min number; the max works perfectly fine). Below is a snippet of my source code

val arrX = Array(10) { 0 }
.
.
.
.

findMinAndMaxButton.setOnClickListener {

        fun getMin(arrX: Array<Int>): Int {
            var min = Int.MAX_VALUE
            for (i in arrX) {
                min =  min.coerceAtMost(i)
            }
            return min
        }

        fun getMax(arrX: Array<Int>): Int {
            var max = Int.MIN_VALUE
            for (i in arrX) {
                max = max.coerceAtLeast(i)
            }
            return max
        }

        output.text = "The Min is "+ getMin(arrX)  + " and the Max is " + getMax(arrX)

        }
    }
}

Just use the built-ins min() and max() see min - Kotlin Programming Language

The problem is in the part you skipped (the dots). You define an array of size 10 with all zeros. If the user enters one 1 that is put into the array, the array has one 1 and nine 0s. The minimum of that is correctly computed as 0.
If you want to have the user to enter “up to” 10 entries instead of exactly 10 entries, you shouldn’t use an array of fixed size 10.
I suggest to use a list instead of an array.

Live long and prosper

1 Like

what does your code look like? - can you show more code ?