java for each 循环中 if 语句的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10309264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:29:40  来源:igfitidea点击:

Return value of if statement in a for each loop

javaif-statementforeachreturn

提问by Sasha

I have this method which uses a for each loop with a if statement in it

我有这个方法,它在每个循环中使用一个 if 语句

public static Apartment getApartment(String aNumber)

//for loop to iterate through the list of apartments         
{   
for (Apartment x : listOfApartments) 
  { 
  // Variable to hold the value of returned apartment    
  if (x.getApartmentNo().equalsIgnoreCase(aNumber))
  { Apartment chosen = x;
  }
  else 
  {JOptionPane.showMessageDialog(null, "Apartment not found");
  }

}  
return chosen;
} 

I am getting an error that Symbol chosen not found. I think I have declared the variable in wrong place. Any help? Note: This is a method that takes a String and returns an Object Apartment.

我收到一个错误,未找到选择的符号。我想我在错误的地方声明了变量。有什么帮助吗?注意:这是一个接受一个字符串并返回一个对象单元的方法。

采纳答案by Rytis I

Accepted answer is correct but I would strongly suggest to avoid multiple return statements. Code with multiple returns statements is harder to manage. Might not seem like a big deal yet, but when code grows this can become a real issue.

接受的答案是正确的,但我强烈建议避免多个 return 语句。具有多个返回语句的代码更难管理。可能看起来还不是什么大问题,但是当代码增长时,这可能会成为一个真正的问题。

public static Apartment getApartment(String aNumber)
{   
    Apartment result = null;
    for (Apartment apartment : listOfApartments) 
    {   
        if (apartment.getApartmentNo().equalsIgnoreCase(aNumber))
        {
             result = apartment;
             break;
        }
    }  
    if (result == null)
    {
        JOptionPane.showMessageDialog(null, "Apartment not found");
    }
    return result;
} 

回答by dasblinkenlight

You have to rewrite your loop: you should not make a decision that the apartment is not found until you finish the loop. You do not need to assign the value to the temporary variable either - once the apartment is found, return it right away.

你必须重写你的循环:在你完成循环之前,你不应该做出没有找到公寓的决定。您也不需要将值分配给临时变量 - 一旦找到公寓,立即返回它。

You can report that the apartment is not found only when you finish the loop.

只有当你完成循环时,你才能报告没有找到公寓。

for (Apartment x : listOfApartments) { 
    // Variable to hold the value of returned apartment    
    if (x.getApartmentNo().equalsIgnoreCase(aNumber)) {
        return x;
    }
}
JOptionPane.showMessageDialog(null, "Apartment not found");
return null;

回答by Andrew T

This is a scope issue, Chosen is created in side the if statement.

这是一个范围问题,Chosen 是在 if 语句中创建的。

Declare it outside and set it to null, then the function will either return chosen if the condition is true, or null if it isn't.

在外部声明它并将其设置为 null,如果条件为真,该函数将返回 selected,否则返回 null。

public static Apartment getApartment(String aNumber)

//for loop to iterate through the list of apartments         
{   
Apartment chosen = null;

for (Apartment x : listOfApartments) 
  { 
  // Variable to hold the value of returned apartment    
  if (x.getApartmentNo().equalsIgnoreCase(aNumber))
  { chosen = x;
  }
  else 
  {JOptionPane.showMessageDialog(null, "Apartment not found");
  }

}  
return chosen;
}

回答by Trevor Hickey

what if your condition "x.getApartmentNo().equalsIgnoreCase(aNumber)" evaluates to false?
the Apartment data type "chosen" does not get created!
how can you return something that hasn't been instantiated?

如果您的条件“x.getApartmentNo().equalsIgnoreCase(aNumber)”评估为假怎么办?
未创建“选择”的公寓数据类型!
你怎么能返回一些没有被实例化的东西?

回答by Chris911

Declare the variable 'chosen' before the for loop like this:

在 for 循环之前声明变量 'chosen' ,如下所示:

Apartment chosen = new Apartment();

Also you can break out of the for loop when once you find the apartment you are looking for. If the list is big it might save some time.

当你找到你要找的公寓时,你也可以跳出 for 循环。如果列表很大,可能会节省一些时间。

回答by Carl Manaster

You're correct; you declared chosen in the wrong place. Declare it right before your loop, but assign it (there) to null. That way, it's guaranteed to have a value when you reach the return line.

你是对的;你在错误的地方宣布被选中。在循环之前声明它,但将它(在那里)分配给 null。这样,当您到达返回线时,它可以保证有一个值。

Alternatively, assuming only one apartment will match (or, you don't care which one), you can simply put return x;in the if...true case. And return null after the loop, assuming the loop completes. Also, because you are looping, every apartment that doesn'tmatch will show the "not found" message; you probably only want to display that after the loop has completed without finding an apartment.

或者,假设只有一间公寓会匹配(或者,您不关心哪一间),您可以简单地return x;输入 if...true 情况。并在循环后返回 null,假设循环完成。此外,因为您在循环,所以每个匹配的公寓都会显示“未找到”消息;您可能只想在循环完成后显示,而没有找到公寓。

回答by ricochet1k

The variable chosenin your code was trapped inside the scope it was created in, so it couldn't be used outside of the {}. Also, the else branch of the if statement was triggering before the rest of the for loop ran.

chosen代码中的变量被困在创建它的范围内,因此不能在{}. 此外,if 语句的 else 分支在 for 循环的其余部分运行之前被触发。

You don't really need to save the chosen apartment, you can just return it immediately, like this:

你真的不需要保存选择的公寓,你可以立即返回它,像这样:

public static Apartment getApartment(String aNumber)
{   
    for (Apartment apartment : listOfApartments) 
    {   
        if (apartment.getApartmentNo().equalsIgnoreCase(aNumber))
            return x;
    }  
    JOptionPane.showMessageDialog(null, "Apartment not found");
    return null;
} 

回答by óscar López

A simple (and correct) way to write the method would be:

编写该方法的一种简单(且正确)的方法是:

public static Apartment getApartment(String aNumber) {
    for (Apartment x : listOfApartments)
      if (x.getApartmentNo().equalsIgnoreCase(aNumber))
        return x;
    JOptionPane.showMessageDialog(null, "Apartment not found");
    return null;
}

It's not necessary to declare a local variable for a value that should be returned immediately. Also, the message dialog should be presented only afterthe loop ends, because only then we're sure that no apartment had the number being searched.

没有必要为应该立即返回的值声明局部变量。此外,消息对话框应该只循环结束显示,因为只有这样我们才能确定没有公寓有被搜索的号码。

Regarding the code in the question, you're right: the variable chosenshould have been declared beforethe forloop, so it can be referenced afterthe loop. The way you declared it, it's visible only inside the ifblock.

关于问题中的代码,您是对的:变量chosen应该在循环之前声明for,因此可以在循环之后引用。你声明它的方式,它只在if块内可见。

回答by Ameer Moaaviah

Variable chosenreturned by the function is out of scope here, declare it at the start of the method just before the loop starts.

chosen函数返回的变量在这里超出范围,在循环开始之前的方法开始处声明它。