如何让这段代码交替打印 countA
然后 countB
然后 countA
然后 countB
等等?现在,它打印所有 countA
,然后打印所有 countB
:
System.out.println(name + ":");
System.out.print("[");
for (int a : countA) {
System.out.print(a + "A-");
}
for (int b : countB) {
System.out.print(b + "B, ");
}
System.out.print("]");
最佳答案
每次迭代两次打印
首先,您需要一个循环而不是两个。然后你需要一些交错序列的方法。
最简单的方法是每次迭代只打印两个数组中的元素:
for (int i = 0; i < countA.length; i++) {
System.out.println(countA[i]);
System.out.println(countB[i]);
}
整数序列
另一种可能性是使用更大的循环来交错这些值。因此,使用 int
范围,即两个数组的总大小。
假设您有两个数组,大小均为 3
。然后获取从 0
到 5
的范围,如果您的索引是 even 则打印第一个数组的项目,如果是则打印第二个数组的项目奇数。
为了重新计算数组中的位置,您只需除以 2
(整数除法):
0 -> 0 / 2 = 0 in first array
1 -> 1 / 2 = 0 in second array
2 -> 2 / 2 = 1 in first array
3 -> 3 / 2 = 1 in second array
4 -> 4 / 2 = 2 in first array
5 -> 5 / 2 = 2 in second array
完整的代码是:
for (int i = 0; i < countA.length * 2; i++) {
int indexInArray = i / 2;
if (i % 2 == 0) {
// Even, take from first
System.out.println(countA[indexInArray]);
} else {
// Odd, take from second
System.out.println(countB[indexInArray]);
}
}
显然,如果两个数组的不同长度,它会变得有点棘手。在这种情况下,您将只遍历较小数组的两倍范围,然后稍后迭代较大数组的最后一部分,而不会交替。
迭代器交换
您可以通过使用 Iterator
并交换它们来实现相同的目的:
Iterator<Integer> first = Arrays.asList(countA).iterator();
Iterator<Integer> second = Arrays.asList(countB).iterator();
Iterator<Integer> current = first;
Iterator<Integer> next = second;
while (current.hasNext()) {
System.out.println(current.next());
// Swap
Iterator<Integer> tmp = current;
current = next;
next = tmp;
}
使用这种方法,可以非常容易地针对不同长度的数组进行调整。您只需要将其添加到末尾:
while (next.hasNext()) {
System.out.println(next.next());
}
因为 current
没有元素了,所以之前的循环中止了。由于 next
可能仍然有一些我们遍历它的剩余元素。
Iterator
方法有一个很大的优势,它也适用于未实现 RandomAccess
(基于快速索引的访问)的类,并且它适用于所有 可迭代
,不仅仅是数组。许多类都是Iterable
。缺点是它不能使用原语。
关于java - 交替打印两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51683571/