更新时间:2022-10-30 18:32:33
在评论中回答你的问题。你只能从一个函数返回一个对象。你可以拿另外一个容器并用名字填充它并返回。例如,
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;
}