简体   繁体   中英

Missing return statement error with method that has a return in for loop

I have a method that returns all the names of people in a LinkedList for a plane.

However even though there is a return statement in the method, I'm still getting told there is a missing return statement.

How can I work around this without putting another return statement in? Why isn't it considered valid? Does putting another return statement in change what is returned?

Any feedback is greatly appreciated.

public String check() {

        for (Person person: passengers)
            {
                return person.getName();
            }    
    }

Because if passengers is empty, the loop will never be entered.

If the loop is never entered, assuming the only return statement is in it, we have a serious problem, don't you think ? It's like if there were no return at all.

You need to add another return statement outside of the loop.

Also note that the return will automatically exit the method, so I don't think this is exactly what you wanted as per this sentence in your question :

I have a method that returns all the names of people in a LinkedList for a plane.

Edit

As per your edit, here how you can return a list containing all names :

return passengers.
          .stream()
          .map(Person::getName)
          .collect(Collectors.toList());

Note that you will need to change the signature of your method to

public List<String> check()

In answer to your question in the comments. You can only return a single object from a function. You could take another container and populate it with the names and return that. For example,

public LinkedList<String> check() {

  LinkedList<String> names = new LinkedList<String>();

  for (Person person: passengers) {
    names.add( person.getName() );
  }

  return names;
}

What exactly are you trying to accomplish, here?

Currently, check will only ever return the name of the first passenger. Think about how your program flows and what you want it to do.

To answer your question, you need to have an 'escape' for every possible path in your code. Even if a certain block should always catch and return (not by definition, but just by how you think the code should flow), you need to handle the case such that that block doesn't catch and return. This can be done by either fixing the first block so that it really is a catch-all, or by simply returning or throwing an error if the first block doesn't catch.

ie

public boolean check() {
   ... 
   if (shouldAlwaysBeTrue) return false;
}

doesn't work because shouldAlwaysBeTrue is not true by definition.

public boolean check() {
    ... 
    if (shouldAlwaysBeTrue) return false;
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM