質問

I have a foreach loop that goes

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? e.g.

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

edit-- Right, so would this be possible in a while loop? :o

役に立ちましたか?

解決

No, this cannot be done in an enhanced for-loop.

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.

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:

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. In this case, doesWordMatch can be different for each charArr.

Use an iterator and a standard for-loop with a blank increment statement:

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

Will the boolean variable doesWordMatch change in the for-loop?

If not, I would suggest:

if(doesWordMatch)
  for(Character[] charArr : charSets)
  {
    //dosomething
  }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top