如何在列表中获得最大加倍??只有一个输出,使用Kotlin
我尝试过使用.maxBy.max()和collection.max,但我只能用它打印,说明每个元素都是max如何在列表中获得最大加倍??只有一个输出,使用Kotlin,kotlin,hashmap,max,Kotlin,Hashmap,Max,我尝试过使用.maxBy.max()和collection.max,但我只能用它打印,说明每个元素都是max val fileName = "src/products.txt" var products = HashMap<Int, Pair<String, Double>>() var inputFD = File(fileName).forEachLine { var pieces = it.split(",") print
val fileName = "src/products.txt"
var products = HashMap<Int, Pair<String, Double>>()
var inputFD = File(fileName).forEachLine {
var pieces = it.split(",")
println("Item# Description Price")
println("----- ------------- ------")
for ( (pro,ducts) in products.toSortedMap() ) {
var pax = mutableListOf(ducts).maxBy { it -> it.second }
var highest = listOf<Double>(ducts.second).max()
println("The highest priced record is ${highest}")
}
val fileName=“src/products.txt”
var products=HashMap()
var inputFD=文件名.forEachLine{
var pieces=it.split(“,”)
println(“项目#说明价格”)
println(“--------------”)
对于products.toSortedMap()中的((专业,产品){
var pax=mutableListOf(管道).maxBy{it->it.second}
var highest=listOf(风管数.second).max()
println(“最高价格记录为${highest}”)
}
文件设置如下(111,shoe,9.99)
输出如下所示
最高价格记录是[(裤子,89.99)]
最高价格记录是[(shoes,49.99)]您试图在for循环中打印值,因此它为每个产品打印该值。此外,变量在循环中每次都初始化,因此每个值都是最大值 这是正确的方法。请注意,您可以在不使用可变变量的情况下解决它
val fileName = "src/products.txt"
val products = File(fileName).readLines() //read all lines from file to a list
.map { it.split(",") } // map it to list of list of strings split by comma
.map { it[0] to it[1].toDouble() } // map each product to its double value in a Pair
.toMap() // convert list of Pairs to a Map
println("Item# Description Price")
println("----- ------------- ------")
products.keys.forEachIndexed { index, desc ->
println("$index\t$desc\t${products[desc]}")
}
println("The highest priced record is ${products.maxBy { it.value }}")
您正在尝试打印for循环中的值,因此它会为每个产品打印该值。此外,变量在循环中每次都会初始化,因此每个值都是最大值 这是正确的方法。请注意,您可以在不使用可变变量的情况下解决它
val fileName = "src/products.txt"
val products = File(fileName).readLines() //read all lines from file to a list
.map { it.split(",") } // map it to list of list of strings split by comma
.map { it[0] to it[1].toDouble() } // map each product to its double value in a Pair
.toMap() // convert list of Pairs to a Map
println("Item# Description Price")
println("----- ------------- ------")
products.keys.forEachIndexed { index, desc ->
println("$index\t$desc\t${products[desc]}")
}
println("The highest priced record is ${products.maxBy { it.value }}")
val-maxPriceProduct=products.maxBy{it.value.second}
太棒了!成功了!谢谢!!!val-maxPriceProduct=products.maxBy{it.value.second}
?太棒了!成功了!谢谢!!!谢谢你,你的建议帮了我大忙。我一定是太累了,我没有考虑循环。我无法完全得到上面的答案,但它确实帮助我解决了问题。我得到了一个数据类型错误。我收到了错误的数据类型,因为这是一个错误列表。由于我缺乏经验nce,我不知道如何修复它。谢谢你,你的建议帮助很大。我一定是太累了,我没有考虑循环。我无法得到上面的答案来完全解决问题,但它确实帮助我解决了问题。我得到了一个数据类型错误。我收到了错误的数据类型,我假设它是一个错误列表。由于我缺乏经验,我我不知道怎么修。