我真的很想合并我的两个数组,但我真的不知道我的代码出了什么问题,它一直给我这个结果:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at javaDay3.ArrayExpanding.main(ArrayExpanding.java:17)
我想查看的结果是:
0
1
2
3
4
5
6
7
8
9
0
0
0
0
0
0
0
0
0
0
请帮我找出我的代码有什么问题: 我想使用循环手动组合两个数组
package javaDay3;
public class ArrayExpanding {
public static void main(String[] args) {
int ages [] = {0,1,2,3,4,5,6,7,8,9}; // my first array
for( int i = 0; i < ages.length; i++) {
int temp [] = new int [20];// my bigger and 2nd array
for(int ix = 0; ix < temp.length; ix++) {
for(int ixx = 0; ixx <= temp.length; ixx++) {
temp [0] = ages [0] ;
System.out.println(temp[ixx]);
}
}
}
}
}
我应该添加或删除某些内容,请帮助我,我正在使用 Eclipse
并采用 Java
最佳答案
你可以尝试这个方法:
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
}
您给它列表 (a) 和要添加的元素 (e),它会返回包含添加元素的列表。
如果你想对多个项目执行此操作,你可以循环它,如下所示:
for(int i = 0; i < ages.length; i++) {
addElement(temp, ages[i]);
}
关于java - 在java中组合两个不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474831/