简体   繁体   English

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

[英]Properly Declaring a Multi-Dimensional Array of Type int in Java

I've looked all around stackoverflow, and have found multiple answers to defining a multiple dimensional array in Java. 我到处都是stackoverflow,并找到了在Java中定义多维数组的多个答案。 Heck I even looked back some of my older code and found similar examples with doubles, but for some reason when utilizing the code out of those examples as well as my own code, I'm getting errors in both Eclipse and IntelliJ like the following: 哎呀,我什至回头看了一些较早的代码,并找到了带有双打的类似示例,但是由于某些原因,在利用这些示例以及我自己的代码中的代码时,我在Eclipse和IntelliJ中都遇到了如下错误:

The following does not give me the above error: 以下没有给我上面的错误:

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

The following gives me the above error: 下面给了我上面的错误:

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)

I'm using this to solve problem 28 on Project Euler. 我正在使用它来解决Eu​​ler项目上的问题28。

I guess you placed your code directly in a class. 我猜您直接将代码放在了一个类中。 You need to put it inside a method of a class, like this: 您需要将其放入类的方法中,如下所示:

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

Or you could use a static initializer: 或者,您可以使用静态初始化程序:

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

如果它表示“ {”预期,则您的错误在于此之前的行中。

try these declarations.. I don't know if I got ur point. 尝试这些声明。.我不知道我是否有意思。

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM