我的目标是将array B[]
插入到带有index K
的元素之后的array A[]
中。
我不需要加长A[]
,最后 5 个元素应该消失了。
这就是我到目前为止得到的。真的不介意程序的开始,这只是我必须确定数组的一些额外要求。
例如:
如果我2
插入K
,则数组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 命名约定:变量名称以小写字母开头。
- 省略卷曲括号
{}
通常会导致代码中的错误。您应该始终使用它们。
一种使用 System.arrayCopy 从数组复制到数组b[]
从位置k
复制到数组a[]
的方法
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 = 1;
int length = (a.length - k) > b.length ? b.length : (a.length - k);
System.arraycopy(b, 0, a, k, length);
注意:如果数组b[]
不适合数组a[]
中的剩余空间,并且正如您所说,您不想延长数组a[]
,请只复制直到剩余空间(使用三元条件运算符计算int length
)。