我的目标是将数组 B[]
插入数组 A[]
中具有索引 K
的元素之后。
我不需要延长 A[]
,最后 5 个元素应该消失。
这就是我到目前为止所得到的。不要介意程序的开头,这只是我必须确定数组的一些额外要求。
例如:
如果我将 K
插入为 2
,则数组 A
为
0 2 4 6 8 10 12 14 16 18 0 0 0 0 0
,数组 B 为 20 40 60 80 100
。
最终的数组 A
应如下所示:
0 2 4 20 40 60 80 100 6 8 10 12 14 16 18
public static void main(String[] args) {
int A[] = new int [15];
int B[] = new int [5];
int K, i, j;
Scanner sc = new Scanner(System.in);
Random r = new Random();
for (i=10; i<=14; i++) {
A[i] = 0;
}
System.out.println("Matīss Lavrinovičs RDBD0 171RDB075");
System.out.print("K=");
if (sc.hasNextInt())
K = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
sc.close();
if (K<0 || K>9) {
for (i=0; i<=9; i++)
A[i] = r.nextInt(50);
for (j=0; j<=4; j++)
B[j] = r.nextInt(100 - 50) + 50; }
else
for (i=0; i<=9; i++)
A[i] = i*K;
for (j=0;j<=4;j++)
B[j] = 10*(j+1)*K;
System.out.print("A: ");
i = 0;
while (i < 15) {
System.out.print(" " + A[i]);
if (i==14) System.out.println();
i = i + 1;
}
System.out.print("B: ");
j = 0;
while (j < 5) {
System.out.print(" " + B[j]);
j = j + 1;
}
do {
} while;
最佳答案
您可以使用System.arrayCopy
:
int[] a = new int[] { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 0, 0, 0, 0 };
int[] b = new int[] { 20, 40, 60, 80, 100 };
int k = 2;
System.arraycopy(a, k + 1, a, k + 1 + b.length, a.length - b.length - k - 1);
System.arraycopy(b, 0, a, k + 1, b.length);
我们首先将索引 #2 b.length
之后的值复制到右侧(即 5)。然后我们将 b
的值复制到数组 a
的正确位置。
替代方法:
List<Integer> list = asList(a).subList(0, a.length - b.length);
list.addAll(k + 1, asList(b));
还有一个小辅助方法:
private static List<Integer> asList(int... ints) {
return IntStream.of(ints)
.boxed()
.collect(Collectors.toList());
}
<小时/>
您应该考虑以下因素:
- 您应该遵守 Java 命名约定:变量名称以小写字母开头。
- 像这样省略大括号
{}
通常会导致代码中出现错误。您应该始终使用它们。
关于java - 将一个数组中的数字插入到另一个数组的确切位置(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184795/