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;
}