Search code examples
javaarraysforeachpartial

java for-each loop for partial array


I know how to use the for-each loop to cycle through an entire array like so:

for(int d : arrayname){
    do something

But how do you use the for-each loop to cycle through a partial array, like the one I am trying to do is to use the for-each to cycle through only the months of May-October, i.e. [4] - [9] to calculate the heat index. Here is a snippet of my code that shows what I am trying to do:

// 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] is January and [11] is December


Solution

  • double[] mayOctober = Arrays.copyOfRange(KeyWestHumid, 4, 9);
    

    and foreach mayOctober to do what you asked.

    btw, it is prefered in that case to use conventional loop.