我在搜索“如何在for循环中给出多个条件?”但没有给出直接的答案。
经过一番研究,我找到了正确的方法。条件不应以逗号(,)或分号(;)分隔。我们可以使用&&运算符将这两个条件连接在一起。
for(初始化;condition1 && condition2;增量)
示例:
for(int j= 0; j < 6 && j < ((int)abc[j] & 0xff) ; j++ )
{
//
}希望这对新的Java开发人员有所帮助。
发布于 2011-05-24 14:46:18
您还可以使用"or“运算符,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}发布于 2011-05-24 15:09:36
基本的for语句包括
update
ForInit)
boolean或Boolean (ForStatement)和
如果您需要多个条件来构建ForStatement,那么可以使用标准逻辑运算符(&&、||、|等)。但是-如果事情变得复杂,我建议使用私有方法:
for (int i = 0, j = 0; isMatrixElement(i,j,myArray); i++, j++) {
// ...
}和
private boolean isMatrixElement(i,j,myArray) {
return (i < myArray.length) && (j < myArray[i].length); // stupid dummy code!
}发布于 2011-05-24 14:48:56
可以在for循环中使用多个变量和条件,如下面的示例所示。
for (int i = 1, j = 100; i <= 100 && j > 0; i = i - 1 , j = j-1) {
System.out.println("Inside For Loop");
}https://stackoverflow.com/questions/6106658
复制相似问题