我是新來的新手,一般編碼!這是令人興奮的學習,但一如既往枯燥乏味。我正在編寫一個程序,一個字符需要解決一個迷宮。我沒有在這裏接近完成,但由於某種原因,我在任何長度超過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;
}
}
喜,歡迎來到StackOverflow!你能指出我們到哪裏你得到一個索引越界異常嗎?不是數字,而是線的內容供參考。你可能要考慮的一件事是SSCCE:http://sscce.org/ – 2013-03-01 01:08:50