我知道如何使用for-each循环遍历整个数组,如下所示:
for(int d : arrayname){
do something
但是,如何使用for-each循环遍历部分数组,就像我要尝试的那样,就是使用for-each仅遍历5月至10月的几个月,即[4]-[9] ]计算热量指数。这是我的代码的片段,显示了我要执行的操作:
// create array for KeyWestTemp
double[] KeyWestTemp;
KeyWestTemp = new double[12];
// initialize array
KeyWestTemp[0] = 70.3;
KeyWestTemp[1] = 70.8;
KeyWestTemp[2] = 73.8;
KeyWestTemp[3] = 77.0;
KeyWestTemp[4] = 80.7;
KeyWestTemp[5] = 83.4;
KeyWestTemp[6] = 84.5;
KeyWestTemp[7] = 84.4;
KeyWestTemp[8] = 83.4;
KeyWestTemp[9] = 80.2;
KeyWestTemp[10] = 76.3;
KeyWestTemp[11] = 72.0;
// create array for KeyWestHumid
int[] KeyWestHumid;
KeyWestHumid = new int[12];
// initialize array
KeyWestHumid[0] = 69;
KeyWestHumid[1] = 67;
KeyWestHumid[2] = 66;
KeyWestHumid[3] = 64;
KeyWestHumid[4] = 66;
KeyWestHumid[5] = 69;
KeyWestHumid[6] = 67;
KeyWestHumid[7] = 67;
KeyWestHumid[8] = 70;
KeyWestHumid[9] = 69;
KeyWestHumid[10] = 69;
KeyWestHumid[11] = 70;
// for-each loop for calculating heat index of May - October
[0]是一月,[11]是十二月
最佳答案
double[] mayOctober = Arrays.copyOfRange(KeyWestHumid, 4, 9);
并且foreach可能在十月执行您要求的操作。
顺便说一句,在这种情况下,最好使用常规循环。