【问题标题】:How to assign values in one array to another in java如何在java中将一个数组中的值分配给另一个数组
【发布时间】:2021-03-09 00:55:48
【问题描述】:

我有两个数组,我正在尝试分配一个数组的值,即 arrayOne[0] 应该等于 arrayTwo[0] 中的相应索引。 我正在尝试使用 forloop 执行此操作,以便它循环遍历一个数组的索引,按顺序分配值。 到目前为止,我有: for (int a =0; a

我知道这是一个非常基本的问题,但正如我的名字所暗示的那样,我正在努力学习编码。

【问题讨论】:

  • arrayTwo[a] = arrayOne[a];

标签: java arrays for-loop


【解决方案1】:

但是在此之后我迷失了如何创建分配索引 0 = 0 的 for 循环,然后逐步执行此操作。

有很多方法可以复制数组。但是由于您特别要求使用 for 循环解决方案,因此只需创建一个相同大小的新数组并使用 for loop 如图所示对其进行索引。

int [] a = {1,2,3,4,5,6,7};
int [] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
     b[i] = a[i]; // this copies element a[i] to b[i] where i is the index.
}

System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));

打印

[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多