返回java中循环中存在的值

时间:2013-04-05 07:30:34

标签: java loops return-value

我想从循环中返回一个值。 我的代码如下:

public long findLocationId(String location) throws SystemException
    {

        long locId = 1;

        List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);

            for(Location findLoc : locationList)  {
                if(location == findLoc.getLocationName())  {
                    locId = findLoc.getLocationId();

                    **return locId;**
                }
            }

    }

当我尝试将返回值放在循环中时,我收到一条错误,指出要包含一个return语句。

我应该如何更改代码,以便从循环本身返回一个值?

我想返回循环中得到的新locId值,而不是我最初设置为locId = 1的值; 我想返回我从循环中得到的locId的新值

14 个答案:

答案 0 :(得分:3)

这是因为函数中的所有控制流都应以返回long值结束。

在您的情况下,假设列表中没有匹配项,因此将永远不会执行return语句,这就是报告错误的原因。

要解决此问题,您可以在函数末尾添加一个带有默认值的return语句,或者如果您的逻辑允许,您可以抛出一个说明找不到位置的execption。

解决方案1:如果没有匹配则要返回1

public long findLocationId(String location) throws SystemException {
    long locId = 1;
    List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,
            -1);
    for (Location findLoc : locationList) {
        if (location == findLoc.getLocationName()) {
            locId = findLoc.getLocationId();
            break;
        }
    }
    return locId;
}

解决方案2:如果找不到位置,则抛出异常

public long findLocationId(String location) throws SystemException {
    List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,
            -1);
    for (Location findLoc : locationList) {
        if (location == findLoc.getLocationName()) {
            return findLoc.getLocationId();
        }
    }
    throw new SystemException("Unable to find the location");
}

答案 1 :(得分:3)

这是因为location == findLoc.getLocationName()并不总是存在这种情况。即使是这种情况,java编译器也不知道你给程序提供了什么样的输入,所以它告诉你可能存在函数没有返回任何东西的情况,即使它必须返回long。

只需在函数末尾返回-1L或您的pogram可以认为“未找到”的内容。

答案 2 :(得分:3)

这个问题有各种各样的方法。

  1. 使用while循环
  2. 使用具有额外停止条件的循环
  3. 使用中断关键字。
  4. 首先在介绍我们的逻辑之前创建一个模板:

    public long findLocationId(String locationName) throws SystemException
        {
    
            if(locationName == null) { //Here we cover first issue. 
                throw new IllegalArgumentException("THe locationName must not be null");
            }
    
            long locId = Long.MIN_VALUE; //We declare a default value that will be returned if none match found. 
    
            Collection<Location> locationList = getLocationList(); //The location can be read from another method so we are not binded to field.
    
            if(locationList == null || locationList.isEmpty()) {
                return locId; // Or throw an exception about invalid state.
            }
    
    
            //Place for the logic
    
    
            return locId;
    
        }
    

    通常,当我们不知道何时想要停止迭代时,这表明我们应该从while循环开始。

    所以试试吧。

    解决方案1 ​​ - 同时进行。

     Iterator<Location> iterator = locationList.iterator();
    
            while(iterator.hasNext() && Long.MIN_VALUE != locId) {
    
                Location location = iterator.next();
    
                if(locationName.equalsIgnoreCase(location.getLocationName())) {
                    locId = location.getLocationId(); // This will change the locId, so second condition will be no longer true and loop will end.
                }
    
            }
    
      

    专业人士:    - 它的工作原理

         

    缺点:    - 离开迭代器

    我们不应该留下迭代器,因为这很容易出错。这引导我们进入下一个解决方案

    解决方案2 - 我们将模式用于迭代器而不是while。

     for(Iterator<Location> iterator2 = locationList.iterator();iterator.hasNext() && Long.MIN_VALUE != locId;) {
    
                Location location = iterator.next();
    
                if(locationName.equalsIgnoreCase(location.getLocationName())) {
                    locId = location.getLocationId(); // This will change the locId, so second condition will be no longer true and loop will end.
                }
            }
    
      

    赞成     - 它的工作原理

         

    缺点     - 这很复杂,在阅读这段代码时我们必须关注停止。

    如上所述,解决方案不容易阅读,也应该删除。

    解决方案3 - 为什么休息有用。

    for(Location location : locationList) {
    
                if(locationName.equalsIgnoreCase(location.getLocationName())) {
                    locId = location.getLocationId();
                    break;
                }
    
            }
    
      

    赞成    - 有用     - 可读

         

    缺点     - 没有

    结论是代码应该是可读的。使用break,我们指出我们找到了匹配项,我们不想继续进展。

    精细。但是当location被发现时呢?

    OP示例我们返回1L。这不是最佳选择,因为该值很可能用作ID。

    在前面的例子中,我使用了long的min值。这在某些情况下是可以接受的,但是,我们仍然需要验证方法结果,并记录它。

    最终解决方案提供额外的循环退出,即return关键字。

    public long findLocationId(String locationName) throws SystemException
        {
    
            if(locationName == null) { //Here we cover fist issue. 
                throw new IllegalArgumentException("THe locationName must not be null");
            }
    
            Collection<Location> locationList = getLocationList(); //The location can be read from another method so we are not binded to field.
    
            if(locationList == null) {
                throw new IllegalStateException("THe location list was not initialized"); 
            }
    
            for(Location location : locationList) {
    
                if(locationName.equalsIgnoreCase(location.getLocationName())) {
                    return location.getLocationId(); //We exit from the method.
                }
    
            }
    
            throw new SystemException("Could not found location for name:" + locationName); 
    
        }
    

    附加说明

    在示例OP中有location == findLoc.getLocationName(),此代码的问题在于我们不应使用==来比较对象类型(details)。当我们处理String类时,推荐的方法是使用方法String#equals(Object)或'String#equalsIgnoreCase(String)'。对于这个例子,我使用了第二个选项。

答案 3 :(得分:1)

必须有一个默认的return语句。由于只有return语句也是有条件的,编译器会强制您使用默认语句。

public long findLocationId(String location) throws SystemException{

    long locId = 1;
    List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
    for(Location findLoc : locationList)  {
         if(location == findLoc.getLocationName())  {
             locId = findLoc.getLocationId();
                return locId;
         }
    }
    return locId; // default return value
}

答案 4 :(得分:1)

public long findLocationId(String location) throws SystemException
    {

        long locId = 1;

        List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);

            for(Location findLoc : locationList)  {
                if(location == findLoc.getLocationName())  {
                    locId = findLoc.getLocationId();


                }
            }
          return locId;
    }

试试这个你得到了一个

答案 5 :(得分:0)

public long findLocationId(String location) throws SystemException
    {

        long locId = 1;

        List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);

            for(Location findLoc : locationList)  {
                if(location == findLoc.getLocationName())  {
                    locId = findLoc.getLocationId();
                    break;
                }
            }
            return locId;
    }

答案 6 :(得分:0)

这是因为return语句中的if语句是有条件的。因此,如果控件永远不会进入if块,则该方法将保留return值。

因此,在方法的末尾有一个默认的return

答案 7 :(得分:0)

如果您的if声明未找到任何与您的位置相同的位置,则意味着会发生什么。这就是发生此编译错误的原因。因此,您必须在方法结束时添加一个return语句。

public long findLocationId(String location) throws SystemException
{

    long locId = 1;

    List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);

        for(Location findLoc : locationList)  {
            if(location == findLoc.getLocationName())  {
                locId = findLoc.getLocationId();

                **return locId;**
            }
        }
return
}

答案 8 :(得分:0)

如果你不使用更多的循环执行循环,你应该使用break语句从循环中出来。

您不能在for循环中使用return语句,因为此return语句将多次调用。

并且该方法一次只需要一个return语句。
这里break语句将突破最内层循环(此处为循环)。

public long findLocationId(String location) throws SystemException
    {

        long locId = 1;

        List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);

            for(Location findLoc : locationList)  {
                if(location == findLoc.getLocationName())  {
                    locId = findLoc.getLocationId();
                   break;
                }
            }
     return locId;
    }

有关详细信息:
Please visit here

答案 9 :(得分:0)

您的return语句位于“if”语句中,这意味着如果“if”的计算结果为false,则不会达到该语句。您需要在“if”语句之外的return语句。

答案 10 :(得分:0)

问题是:如果不满足循环中的条件,您的方法会返回什么?

您需要返回一个默认值,return语句需要放在for循环之后。

答案 11 :(得分:0)

您的代码中有2个问题。

  1. 一个方法必须只有一个return,但是在for循环中,因为它也是一个条件流(它甚至可能不会运行一次)你必须提供一个备用返回语句。虽然它会返回先发生的任何内容。
  2. 每个流程中都必须有return。但由于您的返回状态为if,如果return为false,则会遗漏if-expression语句。然后,您需要在if之外提供替代退货声明。 (否则编译器将显示错误)
  3. 代码中

        for(Location findLoc:locationList){         if(location == findLoc.getLocationName()){             locId = findLoc.getLocationId();             return locId;         }     }     return locId; //添加这个可以解决问题

答案 12 :(得分:0)

在找不到元素的情况下,您只需添加一个return语句。 琐碎的自足示例:

public class Main {

    public static long findStringIDX(String[] myList, String myString) {

        long locId = 0;

        for (String s : myList) {
            if (myString.equalsIgnoreCase(s)) {
                return locId;
            }
            locId++;
        }
        return -1; // Not found

    }

    public static void main(String[] args) {
        String[] myList = new String[] { "hello", "world", "bobby" };
        System.out.println(findStringIDX(myList, "bobby"));
    }

}

答案 13 :(得分:0)

这样做的简单方法。

public long findLocationId(String location) throws SystemException
{
  long locId = 1; // but i suggest to put -1
  List<Location> locationList = LocationLocalServiceUtil.getLocations(-1,-1);
  for(Location findLoc : locationList)  {
    if(location == findLoc.getLocationName())  {
      return findLoc.getLocationId();
    }
  }
  return locId;
}