我有这种方法为每个循环使用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;
}


我收到找不到选择的Symbol的错误。我认为我在错误的位置声明了变量。
有什么帮助吗?
注意:这是一个采用String并返回Object Apartment的方法。

最佳答案

可接受的答案是正确的,但我强烈建议避免使用多个return语句。具有多个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;
}

关于java - 每个循环的if语句的返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10309264/

10-10 15:06