2D数组尝试在JAVA的if函数中获取相同的值

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

2d Arrays trying to get same value in if function JAVA

问题

public class Canada
{
    // ... (Same code as provided)

    public String getProvinceWhoseCapitalsIs(String city)
    {
        String sameCity = "not computing";
        for (int i = 0; i < provinces.length; i++)
        {
            if (city == null || city.isEmpty())
            {
                throw new IllegalArgumentException("Please enter correct province name");
            }
            if (city.equals(provinces[i][NAME_OF_CAPITAL_CITY]) && city.equals(provinces[i][NAME_OF_BIGGEST_CITY]))
            {
                sameCity = provinces[i][NAME_OF_PROVINCE];
                break;
            }
        }
        return sameCity;
    }
}

Please note that in your original code, you were using the == operator to compare strings. In Java, you should use the .equals() method to compare strings for content equality. I have corrected this in the getProvinceWhoseCapitalsIs method.

英文:

Hi I am near the end of my assignment, but can't seem to get my output values to output large cities in Canada per province that are also the capital city of said province. Below is my code and in a separate box is my method code. Thanks in advance.

public class Canada
{
    public static final int BC = 0;
    public static final int AB = 1;
    public static final int ON = 2;
    public static final int QC = 3;
    public static final int NL = 4;
    public static final int PE = 5;
    public static final int NS = 6;
    public static final int NB = 7;
    public static final int MB = 8;
    public static final int SK = 9;
    public static final int NU = 10;
    public static final int YT = 11;
    public static final int NT = 12;

    public static final int NAME_OF_PROVINCE = 0;
    public static final int NAME_OF_CAPITAL_CITY = 1;
    public static final int NAME_OF_BIGGEST_CITY = 2;

    public String[][] provinces;
    public Canada()
    {
        provinces = new String[13][3];

        provinces[BC][NAME_OF_PROVINCE] = &quot;british columbia&quot;;
        provinces[BC][NAME_OF_CAPITAL_CITY] =&quot;victoria&quot;;
        provinces[BC][NAME_OF_BIGGEST_CITY] =&quot;vancouver&quot;;

        provinces[AB][NAME_OF_PROVINCE] = &quot;alberta&quot;;
        provinces[AB][NAME_OF_CAPITAL_CITY] =&quot;edmonton&quot;;
        provinces[AB][NAME_OF_BIGGEST_CITY] =&quot;calgary&quot;;

        provinces[ON][NAME_OF_PROVINCE] = &quot;ontario&quot;;
        provinces[ON][NAME_OF_CAPITAL_CITY] =&quot;toronto&quot;;
        provinces[ON][NAME_OF_BIGGEST_CITY] =&quot;toronto&quot;;

        provinces[QC][NAME_OF_PROVINCE] = &quot;quebec&quot;;
        provinces[QC][NAME_OF_CAPITAL_CITY] =&quot;quebec city&quot;;
        provinces[QC][NAME_OF_BIGGEST_CITY] =&quot;montreal&quot;;

        provinces[NL][NAME_OF_PROVINCE] = &quot;newfoundland&quot;;
        provinces[NL][NAME_OF_CAPITAL_CITY] =&quot;st johns&quot;;
        provinces[NL][NAME_OF_BIGGEST_CITY] =&quot;st johns&quot;;

        provinces[PE][NAME_OF_PROVINCE] = &quot;prince edward island&quot;;
        provinces[PE][NAME_OF_CAPITAL_CITY] =&quot;charlottetown&quot;;
        provinces[PE][NAME_OF_BIGGEST_CITY] =&quot;charlottetown&quot;;

        provinces[NS][NAME_OF_PROVINCE] = &quot;nova scotia&quot;;
        provinces[NS][NAME_OF_CAPITAL_CITY] =&quot;halifax&quot;;
        provinces[NS][NAME_OF_BIGGEST_CITY] =&quot;halifax&quot;;

        provinces[NB][NAME_OF_PROVINCE] = &quot;new brunswick&quot;;
        provinces[NB][NAME_OF_CAPITAL_CITY] =&quot;fredericton&quot;;
        provinces[NB][NAME_OF_BIGGEST_CITY] =&quot;saint john&quot;;

        provinces[MB][NAME_OF_PROVINCE] = &quot;manitoba&quot;;
        provinces[MB][NAME_OF_CAPITAL_CITY] =&quot;winnipeg&quot;;
        provinces[MB][NAME_OF_BIGGEST_CITY] =&quot;winnipeg&quot;;

        provinces[SK][NAME_OF_PROVINCE] = &quot;saskatchewan&quot;;
        provinces[SK][NAME_OF_CAPITAL_CITY] =&quot;regina&quot;;
        provinces[SK][NAME_OF_BIGGEST_CITY] =&quot;saskatoon&quot;;

        provinces[NU][NAME_OF_PROVINCE] = &quot;nunavut&quot;;
        provinces[NU][NAME_OF_CAPITAL_CITY] =&quot;iqaluit&quot;;
        provinces[NU][NAME_OF_BIGGEST_CITY] =&quot;iqaluit&quot;;

        provinces[YT][NAME_OF_PROVINCE] = &quot;yukon&quot;;
        provinces[YT][NAME_OF_CAPITAL_CITY] =&quot;whitehorse&quot;;
        provinces[YT][NAME_OF_BIGGEST_CITY] =&quot;whitehorse&quot;;

        provinces[NT][NAME_OF_PROVINCE] = &quot;northwest territories&quot;;
        provinces[NT][NAME_OF_CAPITAL_CITY] =&quot;yellowknife&quot;;
        provinces[NT][NAME_OF_BIGGEST_CITY] =&quot;yellowknife&quot;;
    }
}

Below here is my method code that I am attempting to pull output with same largecity in province as capital city in province. Like Toronto is that capital city of province Ontario and is also the largest city in Ontario. Whereas, Vancouver is the largest city in BC, but is not the capital city so null. I have tried a wide variety of combinations where it would either always output not computing or it would just output the city I type.

p.s. I know the 2d array code is atrocious, but it was the way the teacher set up the initial build of this question.

public String getProvinceWhoseCapitalsIs(String city) // return
{
    String sameCity = &quot;not computing&quot;;
    for(int i = 0;i&lt;provinces.length;i++)
    {
        if(city == null || city.isEmpty())
        {
            throw new IllegalArgumentException(&quot;Please enter correct province name&quot;);
        }
        if(city == provinces[i][1] &amp;&amp; city == provinces[i][2])
        {
            city = provinces[i][1];

        }
        break;
    }
    return city;
}

Made some edits to the method and now it is only returning what I type as output...

答案1

得分: 1

我认为问题出在你的循环条件上:

for (int i = 0; i < province[i].length; i++)

注意,在你的情况下,province[i].length 等于 3。

我认为你需要将循环条件改为:

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

这样会执行循环12次(province的长度)。

英文:

i think the problem is with your loop condition

for(int i=0;i&lt;province[i].length;i++)

notice that in your circumstances province[i].length is equal to 3

i think what you need to do is to change you loop condition to

for(int i=0;i&lt;province.length;i++)

which would execute the loop 12 times (length of the province)

答案2

得分: 1

你的代码中存在三个问题:

  1. 你在代码中使用了city == provinces[i][1]city == provinces[i][2]来比较字符串,这不是正确的比较字符串的方式。注意,==只是比较引用,而不是比较字符串的内容。
  2. 你将break语句放在了if块的外面(预期在找到匹配的city时会评估为true)。因此,无论数组provinces中有多少元素,以及是否找到匹配,for循环只会执行一次。
  3. 如果我正确理解了getProvinceWhoseCapitalsIs的目的,它应该返回省份的名称,而不是城市的名称。因此,你应该返回provinces[i][0],而不是provinces[i][1]

如果上述第3点不符合你方法的预期功能,请忽略该点。

更正后的代码如下:

public String getProvinceWhoseCapitalsIs(String city) {
    String province = "";
    if (city == null || city.isEmpty()) {
        throw new IllegalArgumentException("Please enter correct province name");
    }
    for (int i = 0; i < provinces.length; i++) {
        if (city.equalsIgnoreCase(provinces[i][1])) {
            province = provinces[i][0];
            break;
        }
    }
    return province;
}

[更新]

添加以下测试代码:

public class Main {
    public static void main(String[] argv) {
        Canada canada = new Canada();
        System.out.println(canada.getProvinceWhoseCapitalsIs("toronto"));
    }
}

输出:

ontario

[另一个更新]

根据你的评论,我理解你正在寻找一种方法来获取最大的省会城市列表。为了满足这个需求,你需要在class Canada中添加以下方法:

public List<String> getBiggestCapitalCities() {
    List<String> cities = new ArrayList<String>();
    for (int i = 0; i < provinces.length; i++) {
        if (provinces[i][1].equalsIgnoreCase(provinces[i][2])) {
            cities.add(provinces[i][1]);
        }
    }
    return cities;
}

测试代码:

public class Main {
    public static void main(String[] argv) {
        Canada canada = new Canada();
        System.out.println(canada.getBiggestCapitalCities());
    }
}

输出:

[toronto, st johns, charlottetown, halifax, winnipeg, iqaluit, whitehorse, yellowknife]
英文:

There are three problems in your code:

  1. You are using city == provinces[i][1] and city == provinces[i][2] to compare the strings which is not the correct way of comparing strings. Note that == compares just the references; not the content of the strings.
  2. You have put the break statement outside the if block (which is expected to evaluate true when the matching city is found). Because of this, the for loop is getting executed only once irrespective of the number of elements in the array, provinces and whether or not a match is found.
  3. If I understood the purpose of getProvinceWhoseCapitalsIs correctly, it is supposed to return the name of the province and not the city. Therefore, you should return provinces[i][0] instead of provinces[i][1].

You can ignore the 3rd point mentioned above if it is not what your method is intended to do.

Do it as follows:

public String getProvinceWhoseCapitalsIs(String city) {
    String province = &quot;&quot;;
    if (city == null || city.isEmpty()) {
        throw new IllegalArgumentException(&quot;Please enter correct province name&quot;);
    }
    for (int i = 0; i &lt; provinces.length; i++) {
        if (city.equalsIgnoreCase(provinces[i][1])) {
            province = provinces[i][0];
            break;
        }
    }
    return province;
}

[Update]

Posting this update to write the following test code:

public class Main {
	public static void main(String[] argv) {
		Canada canada = new Canada();
		System.out.println(canada.getProvinceWhoseCapitalsIs(&quot;toronto&quot;));
	}
}

Output:

ontario

[Another update]

Based on your comment, I understood that you are looking for a method to get the list of the biggest capital cities. In order to meet this requirement, you need to put the following method into the class Canada:

public List&lt;String&gt; getBiggestCapitalCities() {
	List&lt;String&gt; cities = new ArrayList&lt;String&gt;();
	for (int i = 0; i &lt; provinces.length; i++) {
		if (provinces[i][1].equalsIgnoreCase(provinces[i][2])) {
			cities.add(provinces[i][1]);
		}
	}
	return cities;
}

Test Code:

public class Main {
	public static void main(String[] argv) {
		Canada canada = new Canada();
		System.out.println(canada.getBiggestCapitalCities());
	}
}

Output:

[toronto, st johns, charlottetown, halifax, winnipeg, iqaluit, whitehorse, yellowknife]

答案3

得分: 0

public String getProvinceWhoseCapitalsIs(String city) {
    String sameCity = null;
    for (int i = 0; i < provinces.length; i++) {
        if (city == null || city.isEmpty()) {
            throw new IllegalArgumentException("Please enter correct province name");
        }
        if (provinces[i][1].equals(city)) {
            sameCity = provinces[i][1];
        }
    }
    return sameCity;
}
英文:
public String getProvinceWhoseCapitalsIs(String city) // return
  {
      String sameCity = null;
      for(int i=0;i&lt;provinces.length;i++)
      {
          if(city == null || city.isEmpty())
          {
              throw new IllegalArgumentException(&quot;Please enter correct province name&quot;);
          }
          if(provinces[i][1].equals(city))
          {
              sameCity = provinces[i][1];
          }
      }
      return sameCity;
  }

This is the method that produced the output I needed.

huangapple
  • 本文由 发表于 2020年3月15日 13:16:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/60689947.html
匿名

发表评论

匿名网友

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

确定