我如何使用"用于"对于这种情况

时间:2018-01-12 00:12:07

标签: kotlin

我需要此功能查看某个日期的文件,然后在同一天为每个航班说明有多少人。 到目前为止,我设法得到它说每天有多少人,但我很难说每天每个航班有多少人。

fun interval(reserves: ArrayList<Reserves>, dayInferior: Int, daySuperior: Int) {
    var count = dayInferior
    var person: Int
    for (reserve in reserves) {
        person = 0
        for (reserve in reserves) {
            if (reserve.day == count && reserve.day <= daySuperior) {
                person++
            }
        }
        if (count <= daySuperior) {
            println("${reserve.numFlight} Day $count has $person")
        }
        count++
    }

}

class Reserves {
    var numCc: Int?
    var name: String
    var numFlight: String
    var day: Int

    constructor(numCc: Int?, name: String, numFlight: String, day: Int) {
        this.numCc = numCc
        this.name = name
        this.numFlight = numFlight
        this.day = day
    }
}


fun readFileReserves(fileNameInput: String): ArrayList<Reserves> {
    val reserves: ArrayList<Reserves> = ArrayList()
    val lines = File(fileNameInput).readLines()

    for (line in lines) {
        val parts = line.split(':')
        val numCc = parts[0].toIntOrNull()
        val name = parts[1]
        val numFlight = parts[2]
        val day = parts[3].toIntOrNull()

        if (day == null || numCc == null) {
            println("Invalid day")
        } else {
            val r = Reserves(numCc, name, numFlight, day)
            reserves.add(r)
        }

    }
    return reserves
}

1 个答案:

答案 0 :(得分:0)

我认为@Jocas意味着ReservesdayInferiordaySuperior之间得到fun interval(reserves: List<Reserves>, dayInferior: Int, daySuperior: Int) { val map = mapReserves(reserves) for(day in dayInferior..daySuperior) { map.forEach { val reservesName = it.key.first val reservesDay = it.key.second val reservesCount = it.value.count() if (reservesDay == day) print("$reservesName has $reservesCount on day passengers $day") } } } fun mapReserves(reserves: List<Reserves>): Map<Pair<String, Int>, List<Reserves>> { val map = mutableMapOf<Pair<String, Int>, MutableList<Reserves>>() reserves.forEach { val key = it.numFlight to it.day val list = map[key] ?: mutableListOf() list.add(it) map[key] = list } return map } // This is how you write in Kotlin. Your style is Java. class Reserves(var numCc: Int, var name: String, var numFlight: String, var day: Int) // Use abstraction List and MutableList instead of ArrayList fun readFileReserves(fileNameInput: String): List<Reserves> { val reserves = mutableListOf<Reserves>() val lines = File(fileNameInput).readLines() for (line in lines) { val parts = line.split(":") val numCc = parts[0].toIntOrNull() val name = parts[1] val numFlight = parts[2] val day = parts[3].toIntOrNull() if (day == null || numCc == null) { println("Invalid day") } else { val r = Reserves(numCc, name, numFlight, day) reserves.add(r) } } return reserves } 的数量。

os.chdir