简体   繁体   English

向foreach循环添加其他参数

[英]add additional parameters to foreach loop

I have a foreach loop that goes 我有一个foreach循环

boolean doesWordMatch = false;
for(Character[] charArr : charSets)
{
  if(doesWordMatch)
    //dosomething
  else
    break;
}

I was wondering, is there anyway to put the condition into the for loop? 我想知道,是否有条件将条件放入for循环中? eg 例如

for(Character[] charArr : charSets && doesWordMatch == true)
{
  //dosomething
}

edit-- Right, so would this be possible in a while loop? 编辑-是的,这样可以在while循环中实现吗? :o :o

No, this cannot be done in an enhanced for-loop . 不,这不能在增强的for循环中完成

You could try the following: 您可以尝试以下方法:

for (Character[] charArr : charSets) {
    if (!doesWordMatch) {
        break;
    }
    //do interesting things
}

I believe this is also more concise than having everything in the looping declaration. 我相信这比在循环声明中包含所有内容更简洁。

If you just want the "if" block out of the for loop, then you can do it the old-fasioned way. 如果您只是想让“ if”块退出for循环,那么您可以采用老式的方法。

Iterator<Character[]> i=charSets.iterator();
for(Character[] charArr=i.next(); i.hasNext() && doesWordMatch == true; charArr=i.next() ) {
        // do something
}

If what you want is to create a mapping between charArr and doesWordMatch : 如果要在charArrdoesWordMatch之间创建一个映射:

Map<Character[], Boolean> map = new HashMap<>();
map.put(charArr, doesWordMatch);

for(Map.Entry<Character[], Boolean> myEntry : map.entrySet()) {
    if(myEntry.getValue()) {
        // do something with myEntry.getKey();
    } else {
        break;
    }
}

I'm not sure if that's what you're looking for, but I can't think of any other reason for wanting the doesWordMatch variable into the loop. 我不确定这是否是您要查找的内容,但是我无法想到将doesWordMatch变量放入循环中的其他原因。 In this case, doesWordMatch can be different for each charArr . 在这种情况下,对于每个charArrdoesWordMatch可以不同。

Use an iterator and a standard for-loop with a blank increment statement: 使用迭代器和带有空白增量语句的标准for循环:

Character[] curr;
for(Iterator<Character[]> iter = charSets.iterator(); iter.hasNext() && doesWordMatch;) {
  curr = iter.next();
  // ...
}

Will the boolean variable doesWordMatch change in the for-loop? 布尔变量didWordMatch是否会在for循环中更改?

If not, I would suggest: 如果没有,我建议:

if(doesWordMatch)
  for(Character[] charArr : charSets)
  {
    //dosomething
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM