我正在尝试遍历一个集合以找到一个项目。如果找到该项目,我希望它打印一条消息,如果未找到该项目,则打印另一条消息。到目前为止,它可以工作,但它会为集合中的每个项目打印一条消息,而我只想显示一条消息:如果找到该项目的价格或未找到的消息。我知道这是由于 for 循环而发生的,但我不知道如何让它只显示一次未找到的消息并遍历整个集合。
这是代码:
fun getarticleout(code:String) {
fun onSuccess(price: Int): String {
return "Price is $price"
}
fun onError(): String {
return "Article not found"
}
for (i in house.articles) {
if (i.code.equals(code)) {
val price = calculatePrice(
articleType = i.articleType,totalTime = i.totalTime.toInt(),hasCard = !i.hasCard.isnullOrEmpty()
)
println(onSuccess(price))
house.articles.remove(i)
} else {
println(onError())
}
}
}
只是为了澄清:
data class House(val articles: MutableSet<Articles>)
data class Articles(val code: String,var articleType: ArticleType,var totalTime: Calendar,var hasCard:String?=" ")