Java – 循环2d数组以查找值不起作用的索引
我知道我在这段代码中的某处出现了错误,但我无法弄明白。 player1.getId(); 返回值1只是为了让您知道。 我正在尝试打印值为1的数组的索引。在代码的最后,我期望currentX为0,currentY为0,但它们都是9.任何帮助都是超级的。
int[][] grid = { {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {3, 3, 3, 3, 3, 3, 3, 3, 3, 3} }; int currentX = 0; int currentY = 0; grid[0][0] = player1.getId(); grid[0][9] = 2; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == player1.getId()); { currentX = i; currentY = j; } System.out.print(grid[i][j]); } } System.out.println(); System.out.println("Player1 is currently in row " + currentX + " and column " + currentY);
删除if (grid[i][j] == player1.getId());
末尾的分号( ;
if (grid[i][j] == player1.getId());
考虑如何使用java语句
if
语句的表达式为true
, if
java的if
语句执行它的块代码。 半冒号结束了java的声明。 如果在if语句之后放入空的半冒号,则将其视为空语句。 所以, if
语句在执行if
结尾处有半冒号的语句时什么都不做。 Java编译器编译代码的方式如下。
if (grid[i][j] == player1.getId()){ //nothing here } { currentX = i; currentY = j; }
看看当其他类型的声明最后有半结肠时会发生什么。
-
循环
while (expression); { //something goes here }
初始化while
循环时,条件可以为true
或false
。 如果条件为true
则会产生无限循环。 在线后没有任何东西会执行。 如果expression为false
,则执行while
循环的预期内容。
-
switch (integer);
和catch (Exception e);
它无法编译并获得exception{ expected
这里的条件为true
(如果player1.getId() == 1
):
if(grid[i][j] == player1.getId());
但是代码包含一个逻辑错误:这里有一组运算符 – 空运算符 ;
它将被执行……
currentX
和currentY
总是等于数组的长度。
currentX = grid.length; currentY = grid[0].length;