的问题是有你想达到和你的方法是什么之间的不匹配。您试图确定该城市是否有效,如果是,请打印出一些数据。但是,你在做什么,而不是被检查,如果特定行有一个有效的城市,这导致对每次迭代正在执行的if声明;因此多重“不是有效的城市”的结果。您的if声明为时尚早。
尝试这样:
/* Grabs all the rows in loadData() with a matching city.
* Which means that if the list is empty, then the city is invalid.
*/
def cityData = loadData().findAll { it[0] == getInputSearch }
if(cityData) {
cityData.each { row ->
row[1].each { column ->
println column
}
println()
}
} else {
println "${getInputSearch} not a valid city"
}
如果你感觉花哨,有喜欢的方式更流/管材:
loadData()
.findAll { it[0] == getInputSearch }
.with {
/* asBoolean() tries to coerce the List into a boolean.
* An empty list is False, while a non-empty list is True
*/
if(!delegate.asBoolean()) println "${getInputSearch} not a valid city"
delegate // Return the list itself so that if it's not empty the process will continue.
}.each { row ->
row[1].each { column ->
println column
}
println()
}