【问题标题】:Escaping inner loop and go to the outer loop after action is done操作完成后转义内循环并转到外循环
【发布时间】:2020-05-29 01:56:55
【问题描述】:

BigestCountries 类有一个代码。

它由2个数组组成:

private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;
public String[] getCountriesFoundedBetween(int min, int max){
    int countriesMatched;
    countriesMatched = 0;  
    String[] countriesFoundedBetween;

    if(biggestCountries == null || biggestCountries.length == 0){
         return null;
    }

    for(int i = 0; i < biggestCountries.length; i++){
        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){

            System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
            countriesMatched++;
        }
    }

    if(countriesMatched > 0){
        countriesFoundedBetween = new String[countriesMatched];
    } else {
        return null;
    }

    for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES

        String countryMatched = null;
        System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);

        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
            for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?

                countryMatched =  biggestCountries[i][COUNTRY_NAME];
                countriesFoundedBetween[j] = countryMatched;
                System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);

            }      
        }      
    }

    return countriesFoundedBetween;
}

不幸的是,它无法从内部循环中逃脱,并将匹配的国家重新写入新生成的数组的所有行。

【问题讨论】:

  • 你有三个循环,你想在最里面的循环满足某些条件后逃到最外面的循环?
  • 是的,有些国家的信息分布在 2 个不同的阵列上。我需要遍历一个数组 - 捕获一些数据,然后遍历另一个数组并将国家/地区名称添加到我的最后一个数组countriesFoundedBetween。在上面的屏幕截图中,长度是正确的——确实有 6 个国家符合条件。但这些并非都是澳大利亚人。
  • 为什么不设置第一个嵌套循环可以测试的标志后从最内层循环中断,如果为真,则中断到第一个循环?
  • 你只需要一个标记为break
  • 好主意,但我相信我不知道如何正确实施它。我试过这个jmp.sh/pNqmiCB,但它似乎不起作用。

标签: java arrays for-loop nested-for-loop


【解决方案1】:

方法getCountriesFoundedBetween()可以不同的实现,不需要嵌套循环,如下。

private static String[] getCountriesFoundedBetween(int min, int max) {
    if (max < min) {
        throw new IllegalArgumentException("'max' less than 'min'");
    }
    String[] countriesFoundedBetween;
    int countriesMatched = 0;
    int[] indexes = new int[biggestCountries.length];
    if (biggestCountries != null && biggestCountries.length > 0) {
        for (int i = 0; i < biggestCountries.length; i++) {
            if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
               countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                indexes[countriesMatched++] = i;
            }
        }
        countriesFoundedBetween = new String[countriesMatched];
        for (int i = 0; i < countriesMatched; i++) {
            countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
        }
    }
    else {
        countriesFoundedBetween = new String[0];
    }
    return countriesFoundedBetween;
}

上面的代码还返回一个空数组而不是 null,这对于返回数组的方法来说更可取。

这是一个使用人口来确定最大国家/地区的完整示例。

public class Countrys {
    private static final int  CHINA      = 0;
    private static final int  INDIA      = 1;
    private static final int  U_S_A      = 2;
    private static final int  INDONESIA  = 3;
    private static final int  PAKISTAN   = 4;
    private static final int  BRAZIL     = 5;
    private static final int  NIGERIA    = 6;
    private static final int  BANGLADESH = 7;
    private static final int  RUSSIA     = 8;
    private static final int  MEXICO     = 9;

    private static final int  COUNTRY_NAME = 0;
    private static final int  COUNTRY_CONTINENT = 1;
    private static final int  COUNTRY_POPULATION = 0;
    private static final int  COUNTRY_AGE_FOUNDED = 1;

    private static int[][] countryData = new int[][]{{1_427_647_786, 1949},
                                                     {1_352_642_280, 1950},
                                                     {  328_239_523, 1776},
                                                     {  273_523_615, 1945},
                                                     {  220_892_340, 1947},
                                                     {  210_147_125, 1889},
                                                     {  206_139_589, 1960},
                                                     {  164_689_383, 1971},
                                                     {  144_384_244, 1991},
                                                     {  128_932_753, 1810}};
    private static String[][] biggestCountries = new String[][]{{"China"     , "Asia"},
                                                                {"India"     , "Asia"},
                                                                {"U.S.A."    , "North America"},
                                                                {"Indonesia" , "Asia"},
                                                                {"Pakistan"  , "Asia"},
                                                                {"Brazil"    , "South America"},
                                                                {"Nigeria"   , "Africa"},
                                                                {"Bangladesh", "Asia"},
                                                                {"Russia"    , "Europe"},
                                                                {"Mexico"    , "North America"}};

    private static String[] getCountriesFoundedBetween(int min, int max) {
        if (max < min) {
            throw new IllegalArgumentException("'max' less than 'min'");
        }
        String[] countriesFoundedBetween;
        int countriesMatched = 0;
        int[] indexes = new int[biggestCountries.length];
        if (biggestCountries != null && biggestCountries.length > 0) {
            for (int i = 0; i < biggestCountries.length; i++) {
                if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
                   countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                    indexes[countriesMatched++] = i;
                }
            }
            countriesFoundedBetween = new String[countriesMatched];
            for (int i = 0; i < countriesMatched; i++) {
                countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
            }
        }
        else {
            countriesFoundedBetween = new String[0];
        }
        return countriesFoundedBetween;
    }

    public static void main(String[] args) {
        String[] result = getCountriesFoundedBetween(1950, 1980);
        System.out.println(Arrays.toString(result));
    }
}

运行上述代码会产生以下输出:

[India, Nigeria, Bangladesh]

【讨论】:

    【解决方案2】:
    1. 如果你将一个 Class 命名为 BigestCountries,它仍然有一个属性 biggestCountries,它是一个数组,包含有关最大国家的信息,我认为你没有利用 OO 的潜力。
    2. 您可以使用 Class 来表示 Country 的数据。通过数据封装,您可以摆脱嵌套数组,从而摆脱嵌套循环和控制流语句(break、continue 等)、查找索引常量、保持biggestCountriescountryData 之间的索引同步等。
    3. 您的代码两次执行相同的任务。第一个循环计算匹配的国家并初始化一个数组。第二个循环实际上将匹配的国家名称放入数组中。
    4. Java 集合框架提供动态大小的数据结构。我在这里使用ArrayList
    5. 我认为ageFound应该命名为yearFound

    重构你的代码

    Country.java

    public class Country {
    
        private String name;
        private int population;
        private int yearFound;
        private String continent;
    
        public Country(String name, String continent, int year, int population) {
            this.name = name;
            this.population = population;
            this.continent = continent;
            this.yearFound = year;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getPopulation() {
            return population;
        }
    
        public void setPopulation(int population) {
            this.population = population;
        }
    
        public String getContinent() {
            return continent;
        }
    
        public void setContinent(String continent) {
            this.continent = continent;
        }
    
        public int getYearFound() {
            return yearFound;
        }
    
        public void setYearFound(int yearFound) {
            this.yearFound = yearFound;
        }
    
        @Override
        public String toString() {
            return "Country [name=" + name + ", population=" + population + ", yearFound=" + yearFound + ", continent="
                    + continent + "]";
        }
    
    }
    

    BiggestCountries.java

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class BiggestCountries {
    
        private List<Country> countries = new ArrayList<Country>() {
            {
                add(new Country("China", "Asia", 1949, 1433783686));
                add(new Country("Canada", "North America", 1867, 37590000));
                add(new Country("United States", "North America", 1776, 328200000));
            }
        };
    
        public List<Country> getCountriesFoundedBetween(int min, int max) {
            List<Country> matchedCountry = new ArrayList<Country>();
            Iterator<Country> itrCoutnry = countries.iterator();
    
            while (itrCoutnry.hasNext()) {
                Country country = itrCoutnry.next();
                int yearFound = country.getYearFound();
                if (min < yearFound && max > yearFound) {
                    matchedCountry.add(country);
                }
            }
            return matchedCountry;
        }
    
    }
    

    试运行

    public static void main(String[] args) {
    
        List<Country> matchedCountries = new BiggestCountries().getCountriesFoundedBetween(1700, 1899);
        System.out.println(matchedCountries);
    }
    

    结果

    [Country [name=Canada, population=37590000, yearFound=1867, continent=North America], Country [name=United States, population=328200000, yearFound=1776, continent=North America]]
    

    【讨论】:

      猜你喜欢
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2019-04-09
      • 2014-07-19
      • 2014-12-14
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多