[英]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. 我正在为大型系统开发原型,但是遇到了一个问题,需要使用for循环从两个不同的数组中获取值。 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.
仅供参考ArrayOne将始终具有+1长度的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: 只需在每次打印前确保
i
在第二个数组的范围内:
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
ArrayOne将始终具有+1长度的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 您可以运行最大长度为ArrayTwo(较短的那个)的循环,然后打印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. 请注意,如果条件
ArrayOne.length == ArrayTwo.length + 1
不成立,则此操作将中断或无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.