0
我正在做關於數組和while循環在java中的作業。 問題是創建一個名爲public int getPopulation(String province)
的方法,該方法返回該省的人口。如果沒有這樣的省份,則返回一個稱爲NO_SUCH_PROVINCE
的常量,該常數設置爲-1。但我無法得到我想要的。如何獲得省的人口
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;
}
當你說你沒有得到你想要的結果時,你是什麼意思?有錯誤嗎?你期待什麼輸出? – PakkuDon
'if(province.equals(provinces [i]))' –
@ScaryWombat快速撥號時是否有重複的內容?你擊敗了我;) –