有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为2D数组的元素赋值

我想创建一个二维数组并初始化一个元素。这是我的密码。类似的代码,用C++语言工作,但不在java中使用。p>

class Test{
    int[][] matrix = new int[3][3];
    matrix [1][1] = 2;
}

共 (3) 个答案

  1. # 1 楼答案

    此代码需要位于方法或静态块中:

    matrix [1][1]=2;
    

    这很好:

    public static void main (String args[]) {
    
        int[][] matrix=new int[3][3];
        matrix [1][1]=2;
    
        System.out.println( matrix [1][1]);
    }
    
  2. # 2 楼答案

    这应该像下面的代码一样简单。将其放在main方法中,以允许您运行程序。代码不可能在任何地方。我编写了另一种速记技巧,让您能够理解2D阵列

    public class TwoDArray {
    
        public static void main(String[] args) {
    
             int[][] matrix = new int[3][3];
             matrix [1][1] = 2;
    
             //prints 2
             System.out.println(matrix[1][1]);
    
    
             //Alternative technique - shorthand
    
             int[][] numb = {
    
                        {1,2,3},
                        {10,20,30},
                        {100,200,300}
    
                };
    
            //prints 300
            System.out.println(numb[2][2]);
    
    
            //prints all gracefully
                for (int row=0; row<numb.length; row++) {
                    for (int col=0; col<numb[row].length; col++) {
                        System.out.print(numb[row][col] + "\t");
                    }
                    System.out.println();
                }
        }
    
    }
    
  3. # 3 楼答案

    不允许您在类方法或构造函数之外初始化变量。下面的代码应该可以编译

    class Test
    {
        int[][] matrix = new int[3][3];
        public Test()
        {
                matrix [1][1] = 2;
        }
    }