在for循环中返回的方法缺少返回语句错误 [英] Missing return statement error with method that has a return in for loop

查看:270
本文介绍了在for循环中返回的方法缺少返回语句错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



但是,即使在方法中有一个return语句,我仍然可以使用这个方法来返回所有在LinkedList中的人的名字。米仍然被告知有一个失踪的回报声明。



我怎样才能解决这个问题,而不用在另一个返回语句?为什么它不被认为是有效的?

任何反馈都不胜感激。

  public String check(){

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


$ / code $ / pre

解决方案

在评论中回答你的问题。你只能从一个函数返回一个对象。你可以拿另外一个容器并用名字填充它并返回。例如,

  public LinkedList< String> check(){

LinkedList< String> names = new LinkedList< String>(); (人人:乘客){
names.add(person.getName());


}

返回名称;
}


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();
            }    
    }

解决方案

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;
}

这篇关于在for循环中返回的方法缺少返回语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆