逃离内循环并在动作完成后返回外部循环。

huangapple go评论69阅读模式
英文:

Escaping inner loop and go to the outer loop after action is done

问题

以下是翻译好的内容:

有一个名为BigestCountries的类的代码

它由两个数组组成

private String[][] biggestCountries; - 保存国家名称和大洲例如biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - 保存人口和建国年份例如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++) { // 用于遍历countries数组,长度为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++){ // 如何退出内部循环?

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

            }
        }
    }

    return countriesFoundedBetween;
}

很抱歉,它无法从内部循环中跳出,并且会将匹配的国家重新写入新生成的数组的所有行。

英文:

There is a code for the BigestCountries class.

It consists of 2 arrays:

private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = &quot;China&quot;; biggestCountries[CHINA][COUNTRY_CONTINENT] = &quot;Asia&quot;;
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 &lt; biggestCountries.length; i++){
if(countryData[i][COUNTRY_AGE_FOUNDED] &gt;= min &amp;&amp; countryData[i][COUNTRY_AGE_FOUNDED] &lt;= max){
System.out.println(String.format(&quot;%d %s&quot;, countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
countriesMatched++;
}
}
if(countriesMatched &gt; 0){
countriesFoundedBetween = new String[countriesMatched];
} else {
return null;
}
for(int i = 0; i &lt; biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES
String countryMatched = null;
System.out.println(&quot;biggestCountries[i] &quot; + biggestCountries[i][COUNTRY_NAME]);
if(countryData[i][COUNTRY_AGE_FOUNDED] &gt;= min &amp;&amp; countryData[i][COUNTRY_AGE_FOUNDED] &lt;= max){
for(int j = 0; j &lt; countriesFoundedBetween.length; j++){ // how to escape inner loop?
countryMatched =  biggestCountries[i][COUNTRY_NAME];
countriesFoundedBetween[j] = countryMatched;
System.out.println(&quot;countriesFoundedBetween: &quot; + countriesFoundedBetween[j] + &quot;; biggestCountries[i][COUNTRY_NAME]: &quot; + biggestCountries[i][COUNTRY_NAME]);
}      
}      
}
return countriesFoundedBetween;
}

Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.
逃离内循环并在动作完成后返回外部循环。

答案1

得分: 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;
}

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

以下是使用人口确定最大国家的完整示例。

public class Countrys {
    // ...(其他常量和数组)

    private static String[] getCountriesFoundedBetween(int min, int max) {
        // ...(方法实现,与上面代码相同)

    }

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

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

[India, Nigeria, Bangladesh]
英文:

The method getCountriesFoundedBetween() can be implemented differently, without the need for nested loops, as follows.

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

The above code also returns an empty array rather than null which is preferable for methods that return arrays.

Here is a complete example using population to determine the biggest countries.

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[][]{{&quot;China&quot;     , &quot;Asia&quot;},
                                                                {&quot;India&quot;     , &quot;Asia&quot;},
                                                                {&quot;U.S.A.&quot;    , &quot;North America&quot;},
                                                                {&quot;Indonesia&quot; , &quot;Asia&quot;},
                                                                {&quot;Pakistan&quot;  , &quot;Asia&quot;},
                                                                {&quot;Brazil&quot;    , &quot;South America&quot;},
                                                                {&quot;Nigeria&quot;   , &quot;Africa&quot;},
                                                                {&quot;Bangladesh&quot;, &quot;Asia&quot;},
                                                                {&quot;Russia&quot;    , &quot;Europe&quot;},
                                                                {&quot;Mexico&quot;    , &quot;North America&quot;}};

    private static String[] getCountriesFoundedBetween(int min, int max) {
        if (max &lt; min) {
            throw new IllegalArgumentException(&quot;&#39;max&#39; less than &#39;min&#39;&quot;);
        }
        String[] countriesFoundedBetween;
        int countriesMatched = 0;
        int[] indexes = new int[biggestCountries.length];
        if (biggestCountries != null &amp;&amp; biggestCountries.length &gt; 0) {
            for (int i = 0; i &lt; biggestCountries.length; i++) {
                if(countryData[i][COUNTRY_AGE_FOUNDED] &gt;= min &amp;&amp;
                   countryData[i][COUNTRY_AGE_FOUNDED] &lt;= max) {
                    indexes[countriesMatched++] = i;
                }
            }
            countriesFoundedBetween = new String[countriesMatched];
            for (int i = 0; i &lt; 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));
    }
}

Running the above code produces the following output:

[India, Nigeria, Bangladesh]

答案2

得分: 0

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 + "]";
	}
}

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);
}
英文:
  1. If you name a Class BigestCountries still it has an attribute biggestCountries which is an array, holds information about biggest countries, I think you are not utilizing the potential of OO.
  2. You can use Class to represent the data of a Country. With data encapsulation, you can get rid of nested array thus nested loop and control flow statement (break, continue etc), lookup index constant, keep sync-ing the index between biggestCountries and countryData etc.
  3. Your code doing the same task twice. The first loop count the matched country and initialize a array. The second loop actually put the matched country name to the array.
  4. Java collection framework provide data structure with dynamic size. I use ArrayList here
  5. I think ageFound should be named yearFound?

Refactored Your code

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 &quot;Country [name=&quot; + name + &quot;, population=&quot; + population + &quot;, yearFound=&quot; + yearFound + &quot;, continent=&quot;
+ continent + &quot;]&quot;;
}
}

BiggestCountries.java

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

Test Run

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

Result

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

huangapple
  • 本文由 发表于 2020年5月29日 09:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/62077446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定