问题-对于循环,只填充二维数组的第一个位置,而不是整个二维数组



所以我想替换2d数组中的一些元素。这是我已经创建的网格:

Row 0: OOxxxOx
Row 1: xxxxxxx
Row 2: xOxOOxO
Row 3: xxxxxOO
Row 4: xxOxOxO
Row 5: OxOxxxO

我想用"."代替所有的"O",我称之为炸弹爆炸。当炸弹"爆炸"时,元素左侧、右侧、上方和下方的炸弹也会变为"."。这是我的"炸弹爆炸"代码:(try-catch在那里,所以即使有数组索引越界,我的代码也可以继续前进(

try {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j].equals(oldBomb)) {
grid[i][j] = empty;
grid[i][j + 1] = empty;
grid[i][j - 1] = empty;
grid[i + 1][j] = empty;
grid[i - 1][j] = empty;
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
e.getMessage();
}

代码会给我这个输出(顶部的网格是我之前创建的网格(:

Row 0: OxxOxxO
Row 1: OxxOOOO
Row 2: OxxOOxO
Row 3: OOxxxOx
Row 4: OxxOOxx
Row 5: OOxOOOx
Row 0: ..xOxxO
Row 1: OxxOOOO
Row 2: OxxOOxO
Row 3: OOxxxOx
Row 4: OxxOOxx
Row 5: OOxOOOx

正如你所看到的,只有第一颗炸弹爆炸,而另一颗没有。有人能帮我吗?为什么只有一个元素发生了变化,而其他元素却没有?

非常感谢。

尝试在此处运行:https://onlinegdb.com/Bkg7lCDqLI

import java.io.*;
public class Main
{
public static void main(String[] args) {

char playground[][]={{'0','0','x','x','x','0','x'},
{'x','x','x','x','x','x','x'},
{'x','0','x','0','0','0','0'},
{'x','x','x','x','x','0','0'},
{'x','x','0','x','0','x','0'},
{'0','x','0','x','x','x','0'}};
System.out.println("Current status of playground");
int rows=6,cols=7;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(playground[i][j]+"  ");
}
System.out.println();
}
System.out.println("Placing bombs now ...boomm");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(playground[i][j]=='0'){
playground[i][j]='.'; 
if (!(i - 1 < 0) && playground[i - 1][j]=='x') {
playground[i - 1][j]='.';
}
if (!(i + 1 > rows-1) && playground[i + 1][j]=='x') {
playground[i + 1][j]='.';
}
if (!(j - 1 < 0) && playground[i][j-1]=='x') {
playground[i][j - 1]='.';
}
if (!(j + 1 > cols-1) && playground[i][j+1]=='x') {
playground[i][j + 1]='.';
}
}
}
};
System.out.println("After bomb blast");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(playground[i][j]+"  ");
}
System.out.println();
}

}
}

try-catch在那里,所以即使存在超出范围的数组索引,我的代码也可以继续前进

那是糟糕的设计。改为使用if语句:

for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j].equals(oldBomb)) {
grid[i][j] = empty;
if (j + 1 < grid[i].length)
grid[i][j + 1] = empty;
if (j > 0)
grid[i][j - 1] = empty;
if (i + 1 < grid.length)
grid[i + 1][j] = empty;
if (i > 0)
grid[i - 1][j] = empty;
}
}
}

相关内容

  • 没有找到相关文章

最新更新