Home > Software design >  KOTLIN - For loop argument is not support function - Looking for alternatives
KOTLIN - For loop argument is not support function - Looking for alternatives

Time:01-03

The code below is for calculating exam results. 5 subject names and 5 points received from those subjects are recorded by the user in empty arrays created.

I have solved everything here. But I want to add "th" "st" "rd" "nd" after "cycle". Which is written "Please type lesson" and "Please type point"

For Example: "Please type 1st point"

But with my code I can: "Please type 1 point"

I tried to execute this process with the "When" condition, but I cannot because the loop argument "cycle" do not support the last() function

For example:

    when (cycle.last()) {
    1 ->  "st"
    2 -> "nd"
}

It will give me a result if worked 11st, 531st, 22nd, 232nd, etc. That's I want

fun main() {

var subject = Array<String>(5){""}
var point = Array<Int>(5){0}


for (cycle in 0 until subject.count()) {

    println("Please type ${cycle 1} lesson")
    var typeLesson = readLine()!!.toString()
    subject[cycle] = typeLesson

    println("Please type ${cycle 1} point")
    var typePoint = readLine()!!.toInt()
    point[cycle] = typePoint
}


var sum = 0
for (cycle in 0 until point.count()) {
    println("${subject[cycle]} : ${point[cycle]}")

    sum = sum   point[cycle]/point.count()
}

println("Average point: $sum")

}

CodePudding user response:

You can divide the number by 10 and get the remainder using %. That is the last digit.

fun Int.withOrdinalSuffix(): String =
    when (this % 10) {
        1 -> "${this}st"
        2 -> "${this}nd"
        3 -> "${this}rd"
        else -> "${this}th"
    }

Usage:

println("Please type ${(cycle 1).withOrdinalSuffix()} lesson")

Note that in English, 11, 12, 13 have the suffix "th", so you might want to do:

fun Int.withOrdinalSuffix(): String =
    if ((this % 100) in (11..13)) { // check last *two* digits first
        "${this}th"
    } else {
        when (this % 10) {
            1 -> "${this}st"
            2 -> "${this}nd"
            3 -> "${this}rd"
            else -> "${this}th"
        }
    }

instead.

  • Related