Question

I have a do while that looks like:

User user = userDao.Get(1);

do
{
 // processing


 // get the next user
 //
 user = UserDao.GetNext(user.Id);

 if(user == null)
       continue;   // will this work?????????????
}
while ( user != null)

If it does work, its going to go to the top of the do statement, and user is null so things are going to break?

Maybe I should rework the loop to a while statement?

Was it helpful?

Solution

The continue makes it jump to the evaluation at the botton so the program can evaluate if it has to continue with another iteration or exit. In this case it will exit.

This is the specification: http://java.sun.com/docs/books/jls/third_edition/html/statements.html#6045

Such language questions you can search it in the Java Language Specification: http://java.sun.com/docs/books/jls/

OTHER TIPS

This really wouldn't be the best way to write this code. If user is null, you'll get a NullPointerException when you try and get user.id the next time around. A better way to do this would be:

User user = UserDao.Get(1);
while(user != null) {
  // do something with the user
  user = UserDao.GetNext(user.id);
}

Why are you testing user in two places? The while condition will terminate the loop when user is null, which is what you want.

Yes, continue will work in a do..while loop.

You probably want to use break instead of continue to stop processing the users, or just remove the if null continue bit completely since the while loop will break out as soon as user is null anyway.

Short answer yes, continue (and break) work properly in do while loops.

As others have pointed out though, from the example it looks like you may be expecting the wrong behavior from continue.

Let's see:

$cat DoWhileContinue.java 
class DoWhileContinue {

    public static void main( String [] args ) {
        int i = 0;
        int y = 0;
        do {
            i++;
            if( i > 100 ) {
                continue;
            }
            y++;

        } while( i < 500  );
        System.out.printf("i=%d, y=%d %n", i, y );
    }
}
$javac DoWhileContinue.java 
$java DoWhileContinue
i=500, y=100 

Yes it does. In this sample you can see y value is 100 because the continue statement was executed and prevented the variable from being increased afterward.

The continue will jump to the loop evaluation statement inside the while which looks redundant as your if and while are evaluating the same thing . I think it would be better to use a break or simply let the while condition do the work (your while condition is already checking it for you)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top