0

I am working on a homework about arrays and while loop in java. The question is to create a method called public int getPopulation(String province) which returns the population of the province. If there is no such province, return a constant called NO_SUCH_PROVINCE, which is an int set to -1. But I cannot get what I want.

public class Country {
public static final int ON = 0;
public static final int QC = 1;
public static final int BC = 2;
public static final int AB = 3;
public static final int MB = 4;

public static final int NO_SUCH_PROVINCE = -1;

private String[] provinces;
private int[] population;

public Country() {
    provinces = new String[5];
    provinces[0] = "Ontario";
    provinces[1] = "Quebec";
    provinces[2] = "British Columbia";
    provinces[3] = "Alberta";
    provinces[4] = "Manitoba";

    population = new int[5];
    population[ON] = 12851821;
    population[QC] = 7903001;
    population[BC] = 4400057;
    population[AB] = 3645257;
    population[MB] = 1208268;
}
public int getPopulation(String province) {
    int i = 0;
    int temp = 0;
    while(i < provinces.length) {
        if(province == provinces[i]) {
            temp = population[i];
        }else {
            temp = NO_SUCH_PROVINCE;
        }
        i++;
    }
    return temp;
}
Ke Wu
  • 3
  • 2

1 Answers1

2

There is an issue with your search algorithm. It keeps going after it finds the solution and then overwrites the correct value. This here, when it finds the value, immediately returns the value and leaves the method. If it cannot find any value, it then returns NO_SUCH_PROVINCE.

The other issue is that noted by Scary Wombat, which is that your code does not compare Strings correctly to find a match.

public int getPopulation(String province) {
    for (int i = 0; i < provinces.length; i++) {    // For objects, always use .equals()
        if (province.equals(provinces[i])) { return population[i]; }
    }
    return NO_SUCH_PROVINCE;
}

Of course, this would be much simpler if one could simply use a HashMap<String, Integer> that stores all the data like a dictionary.

ifly6
  • 5,003
  • 2
  • 24
  • 47