does anyone know how to use an array as a reference to get an element in another array by using for loop or another useful method? For example, I got multiple arrays below, and after I run the program the output array will have
有没有人知道如何使用数组作为参考,通过使用for循环或其他有用的方法获取另一个数组中的元素?例如,我在下面有多个数组,在运行程序之后输出数组将有
int[] array = { 0, 1, 3, 4, 5, 6, 8 };
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
After I run program
我运行程序后
output ={18,19,21,22,23,24,26}
//this is generate through below
output[0]=c[0];
output[1]=c[1];
output[2]=c[3];
output[3]=c[4];
3 个解决方案
#1
1
Since array indexes are usual integer values, they don't need to be hardcoded:
由于数组索引是通常的整数值,因此不需要硬编码:
int[] indeces = { 0, 1, 3, 4, 5, 6, 8 };
int[] values = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
int[] output = new int[indeces.length]
for (int i = 0; i<indeces.length; i++) {
output[i] = values[indeces[i]];
}
(Code untested)
#2
0
You can access the values like that:
您可以访问以下值:
output[i]=c[array[i]];
I'm leaving it to you to assemble the loop around the statement :)
我要把它留给你来围绕声明组装循环:)
#3
0
You can use the below code to achieve this
您可以使用以下代码来实现此目的
int[] array = { 0, 1, 3, 4, 5, 6, 8 };
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
int output [] = new int[array.length];
int cnt =0 ;
for(int a : array){
if(a < c.length && a >= 0){
output[cnt++]=c[a];
}
}
this is a very simple solution there are of course other ways to achieve the same
这是一个非常简单的解决方案,当然还有其他方法可以达到同样的效果
#1
1
Since array indexes are usual integer values, they don't need to be hardcoded:
由于数组索引是通常的整数值,因此不需要硬编码:
int[] indeces = { 0, 1, 3, 4, 5, 6, 8 };
int[] values = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
int[] output = new int[indeces.length]
for (int i = 0; i<indeces.length; i++) {
output[i] = values[indeces[i]];
}
(Code untested)
#2
0
You can access the values like that:
您可以访问以下值:
output[i]=c[array[i]];
I'm leaving it to you to assemble the loop around the statement :)
我要把它留给你来围绕声明组装循环:)
#3
0
You can use the below code to achieve this
您可以使用以下代码来实现此目的
int[] array = { 0, 1, 3, 4, 5, 6, 8 };
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
int output [] = new int[array.length];
int cnt =0 ;
for(int a : array){
if(a < c.length && a >= 0){
output[cnt++]=c[a];
}
}
this is a very simple solution there are of course other ways to achieve the same
这是一个非常简单的解决方案,当然还有其他方法可以达到同样的效果