user4376896
user4376896

Reputation:

print nested loop of arrays with different length

I'm developing a prototype for a large system, but I came across a problem with getting the values from two different arrays using for loop. The problem occurs because both arrays have different lengths but I need them to run in the same loop. FYI ArrayOne will always have +1 length of ArrayTwo. Can anyone think of a way to get the below code working?

Thank you.

for (int i = 0; i < getArrayOne().length; i++) {            
    System.out.print(getArrayOne()[i] + " " + getArrayTwo()[i] + " ");
}

Upvotes: 1

Views: 1069

Answers (1)

nem035
nem035

Reputation: 35501

Just make sure i is within the bounds of the second array each time before you print it:

for (int i = 0; i < getArrayOne().length; i++) {        
    System.out.print(getArrayOne()[i] + " ");
    if(i < getArrayTwo().length) { // check that i is within bounds of ArrayTwo
        System.out.print(getArrayTwo()[i] + " ");
    }
}

Or, since you know that:

ArrayOne will always have +1 length of ArrayTwo

You could just run the loop you have up to the length of ArrayTwo (the shorter one) and then print the remaining element of ArrayOne

int i = 0;
for (; i < getArrayTwo().length; i++) {            
    System.out.print(getArrayOne()[i] + " " + getArrayTwo()[i] + " ");
}
System.out.print(getArrayOne()[i]);

Due note that this will break or not work properly if the condition ArrayOne.length == ArrayTwo.length + 1 isn't true.

Upvotes: 2

Related Questions