如何填充kotlin中的对象数组?

时间:2019-03-18 17:59:10

标签: class oop kotlin

当我开始填充数组和此处的代码

时出现错误
fun main(args :Array<String>){
println(" give the size")
var nbr=readLine()!!.toInt()
    class time(var hour:Int,var minute:Int,var seconde:Int)
class athlete(var name:String,var nombre:Int, var result:time)
var tab=arrayOfNulls<athlete>(50)
for(i in 0 until nbr)
    println("give the name of  ${i+1} athlete")
tab[i].name=readLine()!!
println("give the nombre of the athelte")
tab[i].nombre=readLine()!!.toInt() 
println("give the hours")
 tab[i].time.hour=readLine()!!.toInt()
println("give the minute")
tab[i].time.minute=readLine()!!.toInt()   
println("give the seconds")
tab[i].time.seconde=readLine()!!.toInt()

当我开始填充数组时,错误在readLine中

2 个答案:

答案 0 :(得分:0)

您忘记在for循环中添加brakcets:

fun main() {
    println(" give the size")
    val nbr = readLine()?.toInt() ?: 0

    val tab = arrayOfNulls<Athlete>(nbr)

    for (i in 0 until nbr) {
        val athlete = Athlete()
        val time = Time()

        println("give the name of  ${i + 1} athlete")
        athlete.name = readLine()

        println("give the nombre of the athlete")
        athlete.nombre = readLine()?.toInt()

        println("give the hours")
        time.hour = readLine()?.toInt()

        println("give the minute")
        time.minute = readLine()?.toInt()

        println("give the seconds")
        time.second = readLine()?.toInt()

        athlete.result = time

        tab[i] = athlete
    }
}

class Time {
    var hour: Int? = null
    var minute: Int? = null
    var second: Int? = null
}

class Athlete {
    var name: String? = null
    var nombre: Int? = null
    var result: Time? = null
}

答案 1 :(得分:0)

您需要使用类属性而不是参数。

这是您的代码的外观:

class Time {
    var hour: Int = 0
    var minute: Int = 0
    var seconde: Int = 0
}  
class Athlete {
    var name: String = " "
    var nombre: Int = 0
    var result = Time()
}

fun main(args: Array<String>) {

    println("Give the size")
    var nbr: Int = readLine()!!.toInt()
    var tab1 = arrayOfNulls<Athlete>(50)
    var tab2 = arrayOfNulls<Time>(50)

    for (i in 0 until nbr) {

        println("Give the name of ${i+1} athlete")
        tab1[i]?.name = readLine()!!

        println("Give the nombre of the athelte")
        tab1[i]?.nombre = readLine()!!.toInt() 

        println("Give the hours")
        tab2[i]?.hour = readLine()!!.toInt()

        println("Give the minute")
        tab2[i]?.minute = readLine()!!.toInt() 

        println("Give the seconds")
        tab2[i]?.seconde = readLine()!!.toInt()
    }
}