这个2D数组有什么问题?

时间:2011-11-15 19:13:27

标签: java arrays syntax formatting 2d

我在Java中使用2D数组,这是第一次这样做。我想知道阵列有什么问题,因为我遇到了很多错误......? (可能是一个非常愚蠢的错误)

代码

    int board[21][21] = {{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
  {1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1},
  {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1},
  {1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,1},
  {1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,1},
  {1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,1},
  {1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1},
  {0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0},
  {1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1},
  {0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0},
  {1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1},
  {1,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1},
  {1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1},
  {1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,1,0,1},
  {1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1},
  {1,0,0,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,0,1},
  {1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,1},
  {1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1},
  {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}};

错误列表 Here is a link instead of posting it here since it's a lot of errors

6 个答案:

答案 0 :(得分:3)

删除21.你应该说

int board[][] = ....

创建数组时必须定义数组的维数。例如,您可以说new int[5]并创建5个元素long int数组。但是当你将这个数组赋值给变量时,你会说:int[] arr = new int[5]。这里int[]是一个类型(int数组)。它类似于C中的int *。在定义类型时,不必说数组有多大。你只需要说明它的元素类型是什么以及它将具有多少维度。

答案 1 :(得分:3)

您无法在声明中指定数组的大小。如果删除大小整数,它将编译。但是,在声明变量时,应始终将括号放在变量的类型上,而不是变量本身:

int[][] board;

而不是:

int board[][];

如果要创建具有特定大小的空白数组,则可以使用new运算符执行此操作:

int[][] board = new int[21][21];

但是,如果通过数组初始化定义数组,则永远不会指定大小。

int[][] board = {{...}, ...};

答案 2 :(得分:2)

首先,在声明

中告知二维数组的大小会出现编译错误
int board[21][21]
通常你想这样做:

int board[][] = {{1,2}{1,3}}

这是一个包含2列和2行

的2D数组
 1 2
 1 3

因此,如果您想要一个包含21行和21列的2D数组,您应该这样做:

int board [] [] = {{},{},{},{},{},{},{},{},{},{},{},{},{}, {},{},{],{},{},{},{},{}}

并在内括号之间填写您需要的任何内容。

答案 3 :(得分:1)

将第一行更改为board[][] ={{ all your numbers}},一切正常。

答案 4 :(得分:1)

你的声明是错误的。

 int board[][] = new int[][] {{...

答案 5 :(得分:1)

从声明中删除维度:

int board[][]