我正在编写这门课程用于某些测试目的。
public class Crap {
public static void main(String[] args) {
int[][] k = new int[2][];
k[0] = {1};
k[1] = {2,3};
System.out.println(k[0][0]);
System.out.println(k[0][1]);
System.out.println(k[1][0]);
System.out.println(k[1][1]);
}
}
编译时出现以下错误。
Crap.java:5: error: illegal start of expression
k[0] = {1};
^
Crap.java:5: error: not a statement
k[0] = {1};
^
Crap.java:5: error: ';' expected
k[0] = {1};
^
Crap.java:6: error: ']' expected
k[1] = {2,3};
^
Crap.java:6: error: ';' expected
k[1] = {2,3};
^
Crap.java:6: error: illegal start of type
k[1] = {2,3};
^
Crap.java:6: error: <identifier> expected
k[1] = {2,3};
^
Crap.java:6: error: ';' expected
k[1] = {2,3};
^
Crap.java:6: error: illegal start of type
k[1] = {2,3};
^
Crap.java:6: error: <identifier> expected
k[1] = {2,3};
^
Crap.java:6: error: ';' expected
k[1] = {2,3};
^
Crap.java:7: error: <identifier> expected
System.out.println(k[0][0]);
^
Crap.java:7: error: ']' expected
System.out.println(k[0][0]);
^
Crap.java:7: error: ')' expected
System.out.println(k[0][0]);
^
Crap.java:7: error: ']' expected
System.out.println(k[0][0]);
^
Crap.java:7: error: illegal start of type
System.out.println(k[0][0]);
^
Crap.java:7: error: <identifier> expected
System.out.println(k[0][0]);
^
Crap.java:8: error: <identifier> expected
System.out.println(k[0][1]);
^
Crap.java:8: error: ']' expected
System.out.println(k[0][1]);
^
Crap.java:8: error: ')' expected
System.out.println(k[0][1]);
^
Crap.java:8: error: ']' expected
System.out.println(k[0][1]);
^
Crap.java:8: error: illegal start of type
System.out.println(k[0][1]);
^
Crap.java:8: error: <identifier> expected
System.out.println(k[0][1]);
^
Crap.java:9: error: <identifier> expected
System.out.println(k[1][0]);
^
Crap.java:9: error: ']' expected
System.out.println(k[1][0]);
^
Crap.java:9: error: ')' expected
System.out.println(k[1][0]);
^
Crap.java:9: error: ']' expected
System.out.println(k[1][0]);
^
Crap.java:9: error: illegal start of type
System.out.println(k[1][0]);
^
Crap.java:9: error: <identifier> expected
System.out.println(k[1][0]);
^
Crap.java:10: error: <identifier> expected
System.out.println(k[1][1]);
^
Crap.java:10: error: ']' expected
System.out.println(k[1][1]);
^
Crap.java:10: error: ')' expected
System.out.println(k[1][1]);
^
Crap.java:10: error: ']' expected
System.out.println(k[1][1]);
^
Crap.java:10: error: illegal start of type
System.out.println(k[1][1]);
^
Crap.java:10: error: <identifier> expected
System.out.println(k[1][1]);
^
Crap.java:12: error: class, interface, or enum expected
}
^
答案 0 :(得分:2)
您需要初始化第二个维度数组..语法如下:
k[0] = new int[]{1};
k[1] = new int[]{2,3};
答案 1 :(得分:0)
答案 2 :(得分:0)
Java中的数组是对象,而不是具有标准对象语法的对象。
因此,您必须分配它们,为此您需要使用new运算符。
int[] array = new int[] { 1, 4, 6, 3};
或者用于将数组赋值给二维数组中的元素(正如您所做的那样)
array[3] = new int[] { 2, 4, 6, 8 };
另请注意,由于它们是对象,并且由于您使用的是不规则数组,因此您对取消引用位置(0,1)或(0)(1)的调用将失败,因为数组位于(0) )只有0索引中的项目。