我是新来的,一般来说都是编码新手!学习很有趣,但一如既往的乏味。我正在编写一个 char 需要解决迷宫的程序。我在这里还没有完成,但由于某种原因,我在长度大于 3 的任何数组上都出现了越界异常。我不知道为什么。有测试用例,你可以看到小迷宫打印成功,但是,当我尝试更大的迷宫时,我得到了一个超出范围的异常。
有什么建议吗?
import java.awt.Point;
public class Maze
{
final char WALL = 'x';
final char BOT = 'r';
final char FREE = ' ';
private String[] maze;
private Point position;
private boolean[][] mazeWalls;
public Maze(String[] strings) // constructor to create maze from main as a 2D array
{
maze = strings;
mazeWalls = new boolean[strings[0].length()][strings.length];
for (int i = 0; i < mazeWalls.length; i++)
for (int j = 0; j < mazeWalls[0].length; j++)
{
if (strings[i].charAt(j) == WALL) // this is where it shows the out of bounds error on m[3] or m[4]
mazeWalls[j][i] = true;
else if (strings[i].charAt(j) == BOT)
{
position = new Point(i, j);
}
}
}
public static void main (String[] args)
{
Maze m;
/*m = new Maze(new String[] {
"xxx",
"xrx",
"xxx"});
m = new Maze(new String[] {
"xxx",
"xrx",
"x x"});
m = new Maze(new String[] {
"xxx",
"xr ",
"xxx",});*/
m = new Maze(new String[] {
"xxxxx",
"xr x",
"x x",
"x ",
"x x",
"x x",
"xxxxx"});
/*m = new Maze(new String[] {
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xr r x x",
"x x x",
"x x x ",
"x x x x",
"x x x x",
"x x x x",
"x xxxxxxxxxxxxxxxxxxxxxxxxxx x",
"x x x",
"x x x",
"x x x",
"x x x",
"x x x",
"x x x",
"x x x",
"x xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx",
"x x x",
"x x x",
"x x x",
"x x",
"x x",
"x x",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"});*/
Robot r = new RandomBot();
// Robot r = new RightHandBot();
int c = 0;
System.out.println(m);
while (!m.isRobotOnEdge())
{
c++;
Point move = r.getMove(m);
m.moveTo(move);
System.out.println("Step Count: " + c);
System.out.println(m);
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
public void moveTo(Point p)
{
/*for (int i = 0; i < mazeWalls.length; i++)
for (int j = 0; j < mazeWalls[0].length; j++)
{
if (maze[i].charAt(j) == BOT)
position = p;
}*/
}
public Point getPoint()
{
return (Point)position.clone();
}
public boolean wallObject(Point p)
{
return wallHere(position.x, position.y);
}
public boolean wallHere(int x, int y)
{
return x < 0 || x >= mazeWalls.length || y < 0 || y >= mazeWalls[0].length || mazeWalls[x][y];
}
public boolean isRobotOnEdge()
{
if (position.x == mazeWalls.length - 1 || position.y == mazeWalls[0].length - 1 || position.x == 0 || position.y == 0)
return true;
return false;
}
public String toString()
{
String s = "";
for (int j = 0; j < mazeWalls.length; j++)
{
for (int i = 0; i < mazeWalls[0].length; i++)
{
if (i == position.x && j == position.y)
s += BOT;
else if (mazeWalls[i][j] == true)
s += WALL;
else
s += FREE;
}
s += "\n";
}
return s;
}
}