2016-12-30 293 views
-2

我的代碼工作正常,直到我添加了else塊。如何在if語句中退出for循環? groovy - java

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"); 
    } 
} 

如果我的else塊中添加break,環只能使用一次,如果我沒有它讓打印「無效的城市,」即使這個城市是有效的,直到它到達正確的數組中的索引。 (數據從文本文件btw讀取) 幫助將不勝感激。

+0

你在listArray存儲,並通過返回了什麼loadData()? –

+1

你想實現什麼?如果輸入的文字不在數據中,打印「不是有效的城市」?如果找到匹配後循環結束,並且loadData()[i]'的元素已經打印完了? – JayK

回答

0

的問題是有你想達到和你的方法是什麼之間的不匹配。您試圖確定該城市是否有效,如果是,請打印出一些數據。但是,你在做什麼,而不是被檢查,如果特定行有一個有效的城市,這導致對每次迭代正在執行的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() 
    }