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] + " ");
}
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.
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.