Correctly exiting a for loop...

What is the best way to get out of a for loop

I have :

public boolean find(String name) {
   int i, count = array.count();
   for (i=0;i<count;i++)
     if (array.objectAt(i).equals(name)
       return true;

    return false;
}

Is it alright/good practice to get out of the loop this way? Any downsides to it?

JavaConvertAsked:
Who is Participating?
 
sciuriwareCommented:
public boolean find(String name)
{
   int count = array.count();

   for (int i=0;  i<count;  i++)
   {
      if(array.objectAt(i).equals(name))
      {
         return true;
      }
   }

   return false;
}

// Lots of small errors.

// Yes a return from a loop is correct.

;JOOP!
0
 
sciuriwareCommented:
Before you post code, please compile it first.

;JOOP!
0
 
CEHJCommented:
I would prefer


public boolean find(String name) {
   int i, count = array.count();
   boolean found = false;
   for (i=0;i<count && !found;i++)
     found = array.objectAt(i).equals(name);
   return found;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.