gpt4 book ai didi

Java 扫雷 - ArrayIndexOutOfBounds 异常

转载 作者:行者123 更新时间:2023-12-01 09:54:02 27 4
gpt4 key购买 nike

我是 Java 编程新手,想寻求您的帮助。我正在尝试使用 Java 开发一个简单的扫雷游戏。但是,我不断收到错误“线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:-1位于practice.week.pkg4.PracticeWeek4.main(PracticeWeek4.java:55)”

当我试图在有炸弹的方 block 周围放置数字时,就会发生这种情况。据我所知,也许1已经超出了数组,导致异常发生。但是,我不确定如何捕获错误。将不胜感激任何善意的帮助。

例如:示例输出

1 1 1

1 B 1

1 1 1

这是我的代码片段:

public static void main(String[] args) {
// TODO code application logic here
int rows = 9;
int cols = 9;
char[][] map = new char[rows][cols];
int count = 0;


for(int i = 0; i<map.length; i++)
{
for(int j = 0; j<map[i].length; j++)
{
map[i][j] = '.';
}
}

Random rnd = new Random();
do
{
int x = rnd.nextInt(rows);
int y = rnd.nextInt(cols);

for(int i = 0; i<map.length; i++)
{
for(int j = 0; j<map[i].length; j++)
{


if(map[x][y] != 'B' && x > 0 & y > 0)
{
map[x][y] = 'B';
map[x-1][y-1] = '1';
map[x-1][y] = '1';
map[x-1][y+1] = '1';
map[x][y-1] = '1';
map[x][y+1] = '1';
map[x+1][y-1] = '1';
map[x+1][y] = '1';
map[x+1][y+1] = '1';
count++;
}

}

}
}
while(count < 10);


for(int x = 0; x<map.length; x++)
{
for(int y = 0; y <map[x].length; y++)
{

}
}

for(int x = 0; x<map.length; x++)
{
for(int y = 0; y<map[x].length; y++)
{
System.out.print(map[x][y] + " ");
}
System.out.println("");
}



}

最佳答案

用于设置地雷的 do-while 循环是正确的,但是更新周围 block 的计数的方式导致了 IndexOutOfBoundsException。这两个循环

for(int i = 0; i < map.length; i++)
{
for(int j = 0; j < map[i].length; j++)

没有任何作用。您需要重新排列它以处理多个地雷等,所以为什么不先设置所有地雷:

do
{
int x = rnd.nextInt(rows);
int y = rnd.nextInt(cols);
if (map[x][y] != 'B')
{
map[x][y] = 'B';
count++;
}
} while(count < 10);

然后浏览 map ,计算每个方 block 周围的地雷数量:

for (int x = 0; x < map.length; x++)
{
for (int y = 0; y < map[x].length; y++)
{
if (map[x][y] == 'B')
continue;

// Count the number of mines around map[x][y]
int mines = 0;
for (int xOffset = -1; xOffset <= 1; xOffset++)
{
// This is an important step - without it, we will access elements off the edge of the map
if (x + xOffset < 0 || x + xOffset >= map.length)
continue;

for (int yOffset = -1; yOffset <= 1; yOffset++)
{
// Another check for the edge of the map
if (y + yOffset < 0 || y + yOffset >= map[x].length)
continue;

if (map[x + xOffset][y + yOffset] == 'B')
mines++;
}
}

map[x][y] = "012345678".charAt(mines); // Get the number as a character
}
}

关于Java 扫雷 - ArrayIndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37382243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com