Kotlin中的函数,该函数在输入中取一个月的名称,并返回该月的天数

Kotlin中的函数,该函数在输入中取一个月的名称,并返回该月的天数,kotlin,Kotlin,我不知道我做错了什么 在Kotlin中编写一个函数,该函数在输入中取一个月的名称,并返回该月的天数,无需为此练习担心闰年 你的主报表应该打印一份类似于月日的报表 代码: 我认为您混淆了字符串和变量名。名称为月份的变量不能与包含月份名称的字符串进行比较 对于此问题,有两种解决方案: 有许多分支机构: fun getDate(month: String) { val number = when (month) { "January" -> 31 "F

我不知道我做错了什么

在Kotlin中编写一个函数,该函数在输入中取一个月的名称,并返回该月的天数,无需为此练习担心闰年

你的主报表应该打印一份类似于月日的报表

代码:


我认为您混淆了字符串和变量名。名称为月份的变量不能与包含月份名称的字符串进行比较

对于此问题,有两种解决方案:

有许多分支机构:

fun getDate(month: String) {
    val number = when (month) {
        "January"   -> 31
        "February"  -> 28
        "March"     -> 31
        "April"     -> 30
        "May"       -> 31
        "June"      -> 30
        "July"      -> 31
        "August"    -> 31
        "September" -> 30
        "October"   -> 31
        "November"  -> 30
        "December"  -> 31
        else        -> throw RuntimeException("Invalid month")
    }
    println("The month of $month has $number of days")
}
对于本例中的集合,hashmap:

val months = mapOf(
    "January"   to 31,
    "February"  to 28,
    "March"     to 31,
    "April"     to 30,
    "May"       to 31,
    "June"      to 30,
    "July"      to 31,
    "August"    to 31,
    "September" to 30,
    "October"   to 31,
    "November"  to 30,
    "December"  to 31
)

fun getDate(month: String) {
    val number = months[month] ?: throw RuntimeException("Invalid month")
    println("The month of $month has $number of days")
}

你的问题是什么?为什么这是用JS标记的?我试图让它工作,但它不工作。。。基本上我是在试着让用户写输入,比如说他是一月份,所以这将是一个月的某一天,你需要阅读或者向你的老师询问函数的基本原理。你的代码有太多的错误要解释,而不能建立在上面。函数接受输入并可选地返回输出。您的函数每月接受两次输入和一个月的天数,但不产生任何输出,但您的任务是针对一个函数,该函数每月接受一次输入并返回一次输出,即该月的天数。1-12不是一个月的天数。您好,你知道我如何返回特定月份的天数吗?我怎样才能让用户写一月份。。。如何打印$month的月份有$number个days@forpas对不起,那是个错误。
val months = mapOf(
    "January"   to 31,
    "February"  to 28,
    "March"     to 31,
    "April"     to 30,
    "May"       to 31,
    "June"      to 30,
    "July"      to 31,
    "August"    to 31,
    "September" to 30,
    "October"   to 31,
    "November"  to 30,
    "December"  to 31
)

fun getDate(month: String) {
    val number = months[month] ?: throw RuntimeException("Invalid month")
    println("The month of $month has $number of days")
}