By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,554 Members | 1,146 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,554 IT Pros & Developers. It's quick & easy.

adding a condition to the enhanced for loop

P: n/a
Hello,

I was wondering if it's possible to add a condition to the enhanced for
loop. This is an example of an enhanced for loop:

LinkedList<MyClass> children = new LinkedList<MyClass>();
boolean found = false;

children.add(new MyClass("Extended"));
children.add(new MyClass("Enhanced"));
children.add(new MyClass("Embraced"));

for (MyClass c: children) {
if (c.getName().equals("Enhanced") {
found = true;
}
}

This loop would continue right to the end though, even if "Enhanced" was
found at the first element. I would like to build an extra condition into
the loop, stating that it must continue but only while !found (this means
found == false).

Any ideas how to do this? Or is it not possible with an enhanced for loop?
Should I use a normal loop, and iterate through the elements using an
Iterator?

Kind regards,

--
Jo Vermeulen
Student Computer Science at the tUL
email: jo@lumumba.luc.ac.be
www: http://lumumba.luc.ac.be/jo
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jo Vermeulen wrote:
Hello,

I was wondering if it's possible to add a condition to the enhanced for
loop. This is an example of an enhanced for loop:

LinkedList<MyClass> children = new LinkedList<MyClass>();
boolean found = false;

children.add(new MyClass("Extended"));
children.add(new MyClass("Enhanced"));
children.add(new MyClass("Embraced"));

for (MyClass c: children) {
if (c.getName().equals("Enhanced") {
found = true;
}
}

This loop would continue right to the end though, even if "Enhanced" was
found at the first element. I would like to build an extra condition into
the loop, stating that it must continue but only while !found (this means
found == false).

Any ideas how to do this? Or is it not possible with an enhanced for loop?
Should I use a normal loop, and iterate through the elements using an
Iterator?


I don't think you can add a condition directly to the for loop, but why
not try a break statement?
for (MyClass c: children)
{
// blah blah blah

if (done())
{
break;
}
}
Jul 17 '05 #2

P: n/a
Op Mon, 31 May 2004 13:54:16 +0000, schreef Raymond DeCampo:
I don't think you can add a condition directly to the for loop, but why
not try a break statement?
for (MyClass c: children)
{
// blah blah blah

if (done())
{
break;
}
}


Hmm, haven't thought of it.. That could indeed do the trick. Hope it's
good coding style though :-)

Kind regards,

--
Jo Vermeulen
Student Computer Science at the tUL
email: jo@lumumba.luc.ac.be
www: http://lumumba.luc.ac.be/jo
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.