如何在 Java 中创建一个简单的 4x3 二维数组?

How can I create a simple 4x3 two dimensional array in Java?

我已经用 C++ 写下来了,但是 Java 对我来说更具挑战性。这就是我所拥有的。我只是希望它有 4 行和 3 列初始化为 1-12 并将其打印到屏幕上。我的错误对你来说很明显吗?谢谢!

我收到 13 个错误 :(

including line9:twoDArray[][] not a statement, ; expected, illegal start of expression, all a few times each.

我试过的代码:

import java.util.*;


class twoDimensional array
{ public static void main(String args[])
{
int[][] twoDArray = new int[4][3];

twoDArray[][]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

System.out.print(twoDArray.toString);


}
}

首先,数组(即使是二维数组)不会覆盖 Object.toString。您可以使用 Arrays.deepToString(Object[]) 并在声明时初始化数组。像

int[][] twoDArray = new int[][] { 
        { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } 
};
System.out.println(Arrays.deepToString(twoDArray));

已修改您的代码

import java.util.*;

class twoDimensional array
{ 
    public static void main(String args[]){
      int[][] twoDArray = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
      //For printing array you have to do 
      System.out.print(Arrays.deepToString(twoDArray));
    }
}
import java.util.*;

class twoDimensionalArray
{ 
public static void main(String args[])
{
int[][] twoDArray = new int[][] { 
    { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } 
};
System.out.println(Arrays.deepToString(twoDArray));
}
}

这是完整的工作副本

public class TwoD {

public static void main(String... args)
{
    int [][]twoD = new int[4][3];
    int num = 1;

    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            twoD[i][j] = num;
            num++;
        }
    }

    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            System.out.print(twoD[i][j]+"\t");
        }
        System.out.println("");
    }
}

}