Loops 如何在if-else语句中退出for循环?groovy-java
在添加Loops 如何在if-else语句中退出for循环?groovy-java,loops,if-statement,groovy,exit,Loops,If Statement,Groovy,Exit,在添加else块之前,我的代码运行良好 String getInputSearch = JOptionPane.showInputDialog("city") for(int i=0; i < listArray.length; i++) { if(getInputSearch == loadData()[i][0]) { for(int j=0; j< loadData()[i].length; j++) { println(loa
else
块之前,我的代码运行良好
String getInputSearch = JOptionPane.showInputDialog("city")
for(int i=0; i < listArray.length; i++) {
if(getInputSearch == loadData()[i][0]) {
for(int j=0; j< loadData()[i].length; j++) {
println(loadData()[i][j])
}
println("")
}
else {
println( getInputSearch+ "not a valid city");
}
}
String getInputSearch=JOptionPane.showInputDialog(“城市”)
for(int i=0;i
如果我在else
块中添加break
,循环只工作一次,如果我不这样做,它会继续打印“not a valid city”,即使城市在到达数组中的正确索引之前是有效的。(顺便说一句,数据是从文本文件读取的)
我们将不胜感激 问题在于,你试图实现的目标与你的方法不匹配。您正在尝试确定该城市是否有效,如果有效,请打印一些数据。但是,您要做的是检查特定行是否具有有效的城市,这将导致您的
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()
}
您在listArray中存储了什么,loadData()返回了什么?您希望实现什么?如果输入的文本不在数据中,是否打印“无效城市”?是否应在找到匹配项并打印了
loadData()[i]
的元素后结束循环?