[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Correctly exiting a for loop...

Posted on 2006-05-26
3
Medium Priority
?
171 Views
Last Modified: 2010-03-31
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?

0
Comment
Question by:JavaConvert
  • 2
3 Comments
 
LVL 24

Accepted Solution

by:
sciuriware earned 200 total points
ID: 16770455
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 16770462
Before you post code, please compile it first.

;JOOP!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16770494
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question