gpt4 book ai didi

java - 如何迭代数组并跳过一些?

转载 作者:行者123 更新时间:2023-12-01 20:12:40 25 4
gpt4 key购买 nike

例如,我的 Java 程序中有这个数组:

String nums[] = {"a", "b", "c", "d", "e", "f", "g", "h" ...}

我想编写 for 循环,它会循环遍历数组并获取每个第二个和第三个字母并将它们每个存储在数组中的两个连续索引中,跳过第 4 个,获取第 5 个和第 6 个字母并将每个字母存储在两个连续索引中数组中的索引,跳过第七个并继续对未知大小的数组执行此操作。

所以最终的数组将是 nums2 = {"b", "c", "e", "f", "h", "i"...}

最佳答案

运行并打印 out = b, c, e, f, h, i

public class Skip {
public static String[] transform(String[] in) {
int shortenLength = (in.length / 3) + ((in.length % 3 > 0) ? 1 : 0);
int newLength = in.length - shortenLength;
String[] out = new String[newLength];
int outIndex = 0;
for (int i = 0; i < in.length; i++) {
if (i % 3 != 0) {
out[outIndex++] = in[i];
}
}
return out;
}

public static void main(String[] args) {
String[] nums = {"a", "b", "c", "d", "e", "f", "g", "h", "i" };
String[] out = transform(nums);
System.out.println("out = " + String.join(", ", out));
}
}

关于java - 如何迭代数组并跳过一些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com