java中将2个数组转为二维数组
您好,我正在尝试将两个数组转换为一个二维数组。但是,我不断收到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
这是我的代码:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
我不太确定问题是什么。抱歉,如果问题很愚蠢,我是编码新手!
Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是:
Java数组总是从0开始。所以final23只有[0]和[1]。
任何具有 n 个元素的数组都可以从 0 到 n-1。
The problem is:
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
您的程序还存在第二个问题。
sum
和print
方法中都有这个循环:在 sum 方法中它应该是
并且在 print 方法中
否则你将再次得到 ArrayIndexOutOfBoundsException 。
请注意,仅当两个输入数组具有相同长度时,程序才能正确运行。这可能适合您的目的,但请记住这一点。
There is also a second problem with your program. You have this loop in both
sum
andprint
methods:In sum method it should be
And in print method
Otherwise you'll get
ArrayIndexOutOfBoundsException
again.Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
请
记住,所有数组都是从 0 开始的,甚至是 n 维数组。
Try
Remember, all arrays are 0 based, even n-dimensional ones.