返回Java中循环中存在的值 - java

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

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的新值

参考方案

有多种解决此问题的方法。

使用while循环
用于带有附加停止条件的循环
使用中断关键字。

在介绍我们的逻辑之前,让我们先创建一个模板:

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的最小值。在某些情况下这是可以接受的,但是我们仍然需要验证方法结果并记录下来。

最终的解决方案是附加的循环退出,即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)'。对于此示例,我使用了第二个选项。

Java:找到特定字符并获取子字符串 - java

我有一个字符串4.9.14_05_29_16_21,我只需要获取4.9。数字各不相同,所以我不能简单地获得此char数组的前三个元素。我必须找到最正确的.并将其子字符串化直到那里。我来自Python,因此我将展示Python的实现方法。def foobar(some_string): location = some_string.rfind('.&…

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java:BigInteger,如何通过OutputStream编写它 - java

我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

Java:从类中查找项目名称 - java

仅通过类的实例,如何使用Java反射或类似方法查找项目名称?如果不是,项目名称(我真正想要的是)可以找到程序包名称吗? 参考方案 项目只是IDE使用的简单组织工具,因此项目名称不是类或JVM中包含的信息。要获取软件包,请使用Class#getPackage()。然后,可以调用Package#getName()将包作为您在代码的包声明中看到的String来获取…