【问题标题】:KOTLIN - For loop argument is not support function - Looking for alternativesKOTLIN - For 循环参数不支持功能 - 寻找替代方案
【发布时间】:2022-01-01 16:11:04
【问题描述】:

下面的代码用于计算考试成绩。 5 个主题名称和从这些主题收到的 5 个分数由用户记录在创建的空数组中。

我已经解决了这里的一切。但我想在 "cycle" 之后添加 "th" "st" "rd" "nd"。写成“请输入课程”“请输入点”

例如: "请输入第一个点"

但是用我的代码我可以: "请输入 1 分"

我尝试使用 "When" 条件执行此过程,但我不能,因为循环参数 "cycle" 不支持 last() 功能

例如:

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

如果工作 11st, 531st, 22nd, 232nd, 等,它会给我一个结果。这就是我想要的

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")

}

【问题讨论】:

  • 你知道是11th,而不是11st吗?

标签: kotlin for-loop arguments


【解决方案1】:

您可以将数字除以 10,然后使用 % 获得余数。那是最后一个数字。

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

用法:

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

请注意,在英语中,11、12、13 有后缀“th”,因此您可能想要这样做:

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"
        }
    }

改为。

【讨论】:

  • 是的,我认为最好的办法是把它分解成一个单独的函数——传入一个数字,取回它的序数形式。它使事情保持整洁,并且任何复杂的逻辑都远离您的主循环。
  • @cactustictacs 另一个优点是它可以从其他代码中重用——对于像这样的简单、自包含的功能块很有用,特别是因为它被表示为扩展函数,因此对于IDE 来查找。
猜你喜欢
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 2015-08-28
相关资源
最近更新 更多