user7442193 user7442193 - 3 years ago 52
Java Question

Converting this line of code to a for loop

So in java, This is what I'm trying to execute:

num [0]=list.get(2);
num [1]=list.get(4);
num [2]=list.get(6);
num [3]=list.get(8);


I have an arraylist of integers called list and I want to put the values that are in the even number indices starting at 2 into an array of integers called num in the indices 0,1,2,3,etc. My problem is, I'm trying to do this within a for loop but I'm not sure how to go about it. Here is what I have:

for (int i=0; i<list.size()-2; i++){
num[i] = list.get(i+2);

}


My problem here is, after incrementing i, my arraylist goes to the next index also instead of every other index. I've tried multiple variations of this loop but I keep coming to the same problem.

Answer Source

This should do it:

int max = list.size()/2;
if(list.size()%2==0) max-=1; // prevents IndexOutOfBounds for even list lengths
for (int i=0; i<max; i++){
    num[i] = list.get(i*2 + 2);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download