Re: please explain this simple construct
Robert Klemme wrote:
On 31.10.2006 14:29, Jeffrey Schwab wrote:
jpbisguier@yahoo.ca wrote:
my instructor likes to use this construct in class but never really
explained why/how it works:
while (true)
{
if (something) return; // break from while
}
can someone shed some light how this works?
That is hideous. The loop will execute the block over and over again,
until "something" happens to be true at the same time the if statement
is executed. At that point, the whole function call will suddenly
end. That's different from an traditional "break," which just exits
the current loop. The (IMHO) preferable way to loop looks more like
this:
while(!something) {
//...
}
I don't find a "return" hideous - certainly not more than a "break". In
fact, I usually prefer "return" inside a loop over a "break". The
"return" gives pretty easy short circuit exit
Yep, agree completely. I don't like a return statement being comment
"break from while," though, especially in a course for people who don't
yet know the language.
and IMHO it is far
superior in cases like this:
public Foo findIt( String name ) {
for ( Iterator iter = myFoos.itererator(); iter.hashNext(); ) {
Foo f = (Foo) iter.next();
if ( name.equals( f.getName() ) ) {
return f;
}
}
// alternatively throw an exception
return null;
}
Using the loop condition to break the loop makes this piece of code much
more complex and probably also less efficient.
Maybe, but I still find it clearer, and easier to debug.
package cljp;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
public class Main {
private static PrintWriter out = new PrintWriter(System.out, true);
List<Integer> myInts = Arrays.asList(
new Integer[] { 1, 2, 3, 4, 5 });
public Integer findIt(Integer n) {
Iterator<Integer> iter = myInts.iterator();
Integer i = null;
boolean found = false;
while(iter.hasNext() && !found) {
i = iter.next();
found = (n == i);
}
return found ? i : null;
}
public static void main(String[] args) {
}
}
Kind regards
robert