在Java中正确声明一个int类型的多维数组

时间:2013-08-19 07:55:29

标签: java

我查看了stackoverflow,并找到了在Java中定义多维数组的多个答案。哎呀我甚至回头看了一些我的旧代码并发现了类似的双打示例,但由于某些原因,当使用这些示例中的代码以及我自己的代码时,我在Eclipse和IntelliJ中都遇到如下错误:

以下内容并未给我上述错误:

public class foo
{
    private int[][] bar()
    {
        int[][] test = new int[10][];
        test[0] = new int[100];
        test[1] = new int[500];
    }  
}

以下给出了上述错误:

public class foo
{
   int[][] test = new int[10][];
   test[0] = new int[100];
   test[1] = new int[500];
}




Syntax error on token ";", { expected after this token (for the first line)
Syntax error on token(s), misplaced construct(s) (for the second line)

我正在使用它来解决Project Euler上的问题28。

3 个答案:

答案 0 :(得分:1)

我猜你把代码直接放在了一个类中。你需要将它放在类的方法中,如下所示:

public class Snippet {
    public static void main(String[] args) {
        int[][] test = new int[10][];
        test[0] = new int[100];
        test[1] = new int[500];
    }
}

或者你可以使用静态初始化器:

public class Snippet {
    static int[][] test = new int[10][];
    static {
        test[0] = new int[100];
        test[1] = new int[500];
    }
}

答案 1 :(得分:0)

如果说'{'预期,那么你的错误就在此之前。

答案 2 :(得分:0)

尝试这些声明..我不知道我是否明白你的观点。

int[][] test = new int[][]{
 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
 };
 //change zeroes with your values

int[][] test= new int[3][10];