我如何在if else语句中退出for循环? groovy - java

时间:2016-12-30 22:35:38

标签: 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(loadData()[i][j])
        }
        println("")
    }
    else {
        println( getInputSearch+ "not a valid city");
    }
}

如果我在break区块中添加else,则循环只能运行一次,如果我不打印,则不会打印有效城市,&#34;即使城市有效,直到它到达阵列中的正确索引。 (从btw的文本文件中读取数据) 帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题是你想要实现的目标与你的方法之间存在不匹配。您正在尝试确定城市是否有效,如果是,则打印出一些数据。但是,您正在做的是检查特定行是否具有有效城市,这导致您的<{>每次迭代执行function dz = OdeFunHndlSpngPdlmSym(~, z) % Define Global Parameters global M K L g % Take output from SymDevFElSpringPdlm.m file for fy1 and fy2 and % substitute into z2 and z4 respectively %fy1=thetadd=z(2)= -(M*g*sin(z1)*(L + z3) + M*z2*z4*(2*L + 2*z3))/(M*(L + z3)^2) %fy2=deldd=z(4)=((M*(2*L + 2*z3)*z2^2)/2 - K*z3 + M*g*cos(z1))/M % return column vector [thetad; thetadd; deld; deldd] dz = [z(2); -(M*g*sin(z(1))*(L + z(3)) + M*z(2)*z(4)*(2*L + 2*z(3)))/(M*(L + z(3))^2); z(4); ((M*(2*L + 2*z(3))*z(2)^2)/2 - K*z(3) + M*g*cos(z(1)))/M]; 语句;因此,多个“非有效城市”的结果。你的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"
}
相关问题