简体   繁体   中英

For loop through an Array in Java

I am trying to write a for loop to iterate from a specific index range.

So if a I have an array called data[] with length 10, and I only want to iterate from the 3rd position (index 2) to the 9th position (index 8), how could I go about writing that loop structure?

The sample code is below:

//Trying to iterate from index 2 - 9
for(int i=0; i<data.length && i>2 && i<9; i++)
{
    System.out.println(data[i]);
}

Thanks in advance

Just change the start index & the stop index of your for loop. So the breaking condition of your for lop would be if index (i) becomes greater than or equal to 9 or greater than or equal the length of the array.

for(int i = 2;  i < 9 && i < data.length;  i++)
{
  System.out.println(data[i]);
}

Just write:

for (int i = 2; i < 9; i++) {
    // Do stuff
}

Change it to:

for(int i=2; i<data.length; i++)
{
    System.out.println(data[i]);
}

If the length is fixed(9):

for(int i=2; i<= 9; i++)
    {
        System.out.println(data[i]);
    }

You can do it like: This will iterate the loop from 3rd position to the last index.

Your code definitely isn't valid but I guess it's just a typo. Typically you want this:

for(int i=2 ; i < Math.min(9,data.length) ; ++i)
{
    System.out.println(data[i]);
}

I recommend to use Math.min(8,data.length) instead of simply 8 just in case your array has less than 9 elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM