从输入的1d数组返回2d数组 [英] Returning a 2d array from inputed 1d array
本文介绍了从输入的1d数组返回2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将输入的 1x6
一维数组返回到一个 3x2
的二维数组中.我想我已经弄清楚了,但是在我的代码中,我一直都需要此错误数组,但是找到了 int
.我认为这是由于输入数组是1d数组而不是2d,但是我不确定.有人可以帮我解决这个问题吗?
I want to take the input 1d array that is a 1x6
and return it into a 2d array that is a 3x2
. I think I have figured it out but in my code I keep getting this error array required, but int
found. I think this is due to the input array being a 1d array and not a 2d, but I'm not sure. Could anyone help me to fix this?
示例:
int[] d = {4, 1, 20, 45, 2, 31};
返回2D数组 3x2
输出:
4 1
20 45
2 31
错误:
transmo[j][i] = d[i][j];
array required, but int found
我的下面的代码:
public class mypractice {
public void a_three_by_two(int[] d) {
int transmo[][] = new int[3][2];
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 6; j++) {
transmo[j][i] = d[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(transmo[i][j] + "\t");
}
System.out.println();
}
}
}
推荐答案
您的第一组循环必须与第二组循环相同,否则 transmo [i] [j]
将失败.
Your first set of loops need to be the same as the second set of loops, otherwise transmo[i][j]
will fail.
然后您需要将索引计算到 d
中.
You then need to calculate the index into d
.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
transmo[i][j] = d[i * 2 + j];
}
}
这篇关于从输入的1d数组返回2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文