我应该从#34;人口中获得所有人口#34;超过某个最小值的数组并将它们返回到数组中。我可以为我的新数组获取正确数量的元素,并正确分配最后一个值,但其余值将返回为零!
class Canada {
private String[] provinces;
private int[] populations;
private int[] array;
private int i;
public static final int NO_SUCH_PROVINCE = -1;
public static final int O = 0;
public static final int Q = 1;
public static final int BC = 2;
public static final int A = 3;
public static final int M = 4;
public static final int S = 5;
public static final int NS = 6;
public static final int NB = 7;
public static final int NL = 8;
public static final int PE = 9;
public static final int NT = 10;
public static final int Y = 11;
public static final int N = 12;
public Canada() {
provinces = new String[13];
provinces[O] = "Ontario";
provinces[Q] = "Quebec";
provinces[BC] = "British Columbia";
provinces[A] = "Alberta";
provinces[M] = "Manitoba";
provinces[S] = "Saskatchewan";
provinces[NS] = "Nova Scotia";
provinces[NB]= "New Brunswick";
provinces[NL] = "Newfoundland and Labrador";
provinces[PE] = "Prince Edward Island";
provinces[NT] = "Northwest Territories";
provinces[Y] = "Yukon";
provinces[N] = "Nunavut";
populations = new int[13];
populations[O] = 12851821;
populations[Q] = 7903001;
populations[BC] = 4400057;
populations[A] = 3645257;
populations[M] = 1208268;
populations[S] = 1033381;
populations[NS] = 921727;
populations[NB] = 751171;
populations[NL] = 514536;
populations[PE] = 142204;
populations[NT] = 141462;
populations[Y] = 33897;
populations[N] = 31906;
}
public int[] getPopulatiosnAboveMin(int min) {
int i = 0;
while(i < populations.length) {
if(populations[i] > min){
array = new int[i + 1];
array[i] = populations[i];
}
i++;
}
return(array);
}
}
答案 0 :(得分:0)
每次循环populations.length
时,您都会重新创建数组。这就是为什么它最终只有一个值。
使用for-each
循环尝试此代码(它有点乱,但它应该完成工作):
public int[] getPopulatiosnAboveMin(int min) {
int nextIndex = 0;
int[] firstArray = new int[populations.length];
//Copy values larger then min to firstArray
for(int pop : populations) {
if(pop > min) {
firstArray[nextIndex++] = pop;
}
}
//Trim extra 0 values:
//Count number of non 0 values:
int non0Count = 0;
for (int i : firstArray) {
if (i != 0) {
non0Count++;
}
}
array = new int[non0Count]; //Initialize array with count of valid, non-0 values.
//Copy values from firstArray to array:
int index = 0;
for (int i : firstArray) {
if (i != 0) {
array[index++] = i;
}
}
return array;
}
此外,正如评论中提到的SLaks,考虑创建一个代表您的省(和地区;))的类,或者查看使用地图,例如HashMap。