第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要循環(huán)外返回語句的方法

需要循環(huán)外返回語句的方法

縹緲止盈 2021-04-14 12:19:49
我在這里的方法在Eclipse上遇到問題。我要求Country如果在名為catalog的數(shù)組中找到該對象,則返回一個對象,如果未找到,則返回null。我試圖遍歷目錄并這樣做。但是,java要求我在代碼的for循環(huán)之外添加return語句。但是,當(dāng)我在執(zhí)行該方法時在for循環(huán)外添加return語句時,它將完全忽略for循環(huán),而僅在for循環(huán)外返回該語句。public Country findCountry(String countryname) {    for (int i = 0; i < catalogue.length; i++) {        if (catalogue[i].getName() == countryname) {            return catalogue[i];        } else {            return null;        }    }}編輯:在循環(huán)之前添加了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;    }
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經(jīng)驗 獲得超4個贊

具有流使用率的另一個版本(需要Java 8或更高版本),并且檢查的版本catalogue不是null:


public Country findCountry(String countryName) {

    if (catalogue == null) {

        return null;

    }


    return Arrays.stream(catalogue)

        .filter(country -> country.getName().equals(countryName))

        .findAny()

        .orElse(null);

}


查看完整回答
反對 回復(fù) 2021-04-28
?
狐的傳說

TA貢獻1804條經(jīng)驗 獲得超3個贊

您可以將返回值初始化為null,并且僅在循環(huán)中找到它時才進行設(shè)置:


    public Country findCountry(String countryname) {

        // initialize a Country with null

        Country foundCountry = null;

        // try to find it

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

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

                // set it if found

                foundCountry = catalogue[i];

            }

        }

        // if not found, this returns null

        return foundCountry;

    }


查看完整回答
反對 回復(fù) 2021-04-28
  • 3 回答
  • 0 關(guān)注
  • 296 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號