需要循环外返回语句的方法

我在这里的方法在Eclipse上遇到问题。我要求Country如果在名为catalog的数组中找到该对象,则返回一个对象,如果未找到,则返回null。我试图遍历目录并这样做。但是,java要求我在代码的for循环之外添加return语句。但是,当我在执行该方法时在for循环外添加return语句时,它将完全忽略for循环,而仅在for循环外返回该语句。


public Country findCountry(String countryname) {

    for (int i = 0; i < catalogue.length; i++) {

        if (catalogue[i].getName() == countryname) {

            return catalogue[i];

        } else {

            return null;

        }

    }

}

编辑:在循环之前添加了foundCountry变量,并在之后返回了它。添加一个中断,并使用.equals()比较字符串。获取一个NullPointerException。


public Country findCountry(String countryname) {

        Country foundCountry = null;

        for (int i = 0; i < catalogue.length; i++) {

            if (catalogue[i].getName().equals(countryname)) {

                foundCountry = catalogue[i];

                break;

            }

        }

        return foundCountry;

    }


缥缈止盈
浏览 251回答 3
3回答

UYOU

具有流使用率的另一个版本(需要Java 8或更高版本),并且检查的版本catalogue不是null:public Country findCountry(String countryName) {&nbsp; &nbsp; if (catalogue == null) {&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; return Arrays.stream(catalogue)&nbsp; &nbsp; &nbsp; &nbsp; .filter(country -> country.getName().equals(countryName))&nbsp; &nbsp; &nbsp; &nbsp; .findAny()&nbsp; &nbsp; &nbsp; &nbsp; .orElse(null);}

狐的传说

您可以将返回值初始化为null,并且仅在循环中找到它时才进行设置:&nbsp; &nbsp; public Country findCountry(String countryname) {&nbsp; &nbsp; &nbsp; &nbsp; // initialize a Country with null&nbsp; &nbsp; &nbsp; &nbsp; Country foundCountry = null;&nbsp; &nbsp; &nbsp; &nbsp; // try to find it&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < catalogue.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (catalogue[i].getName().equals(countryname)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // set it if found&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foundCountry = catalogue[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // if not found, this returns null&nbsp; &nbsp; &nbsp; &nbsp; return foundCountry;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java