我想用一组特定的数字填充 Java 中的二维数组。
我的示例数组集:{{7,-4},{8,-2},{9,-1}}
如何在不执行此操作的情况下加载数组?
int[][] x = new int[3][2];
x[0][0] = 7;
x[0][1] = -4;
x[1][0] = 8;
x[1][1] = -2;
x[2][0] = 9;
x[2][1] = -1;
此外,我认为我可以做到这一点,但我得到“错误:非法的表达式开始。”
class Alpha {
int[][] x;
public Alpha () {
x = new int[3][];
x[0] = {7,-4}; <== line where error is located
}
}
最佳答案
试试这个。
你可以像这样初始化二维数组。
int x[][] = {
{7, -4},
{8, -2},
{9, -1}
};
或者
x[0] = new int[] {7,-4};
x[1] = new int[] {8,-2};
x[2] = new int[] {9,-1};
关于java - 在 Java 中向二维数组提供元素,为什么不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977553/