0

So I'm doing some map pathfinding and I keep getting an error

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

However I don't understand how it could be out of bounds. The map is 10,10 therefore the x&y array parts go 0-9.

This is my code

public boolean[][] passable;

public int[][] passCost;

String[][] twoDMap = {
        { ".", ".", ".", ".", ".", "X", ".", ".", ".", "." },// ROW0
        { ".", "X", "X", "X", ".", "X", "X", "X", ".", "." },// ROW1
        { ".", "X", ".", "X", ".", "X", ".", "X", "X", "X" },// ROW2
        { ".", ".", ".", ".", ".", ".", "X", ".", "X", "." },// ROW3
        { ".", "X", "X", "X", "X", "X", "X", "X", ".", "X" },// ROW4
        { ".", ".", ".", ".", ".", ".", ".", ".", "X", "X" },// ROW5
        { "X", "X", ".", ".", ".", ".", "X", "X", ".", "." },// RO6
        { ".", ".", ".", ".", "X", "X", "X", ".", ".", "." },// RO7
        { ".", "X", "X", "X", "X", ".", ".", ".", ".", "." },// ROW8
        { ".", ".", ".", ".", ".", ".", "X", ".", ".", "." } };// ROW9

private void createMap() {
    passable = new boolean[twoDMap.length][twoDMap[0].length];
    passCost = new int[passable.length][passable[0].length];
    System.out.println(twoDMap.length);
    System.out.println(twoDMap[0].length);
    for (int x = 0; x < passable.length; x++) {
        for (int y = 0; y < passable[x].length; y++) {
            passCost[x][y] = 1;
            System.out.print(twoDMap[x][y]);
            passable[x][y] = twoDMap[y][x].charAt(x) == 'X' ? false
                    : true;
        }
        System.out.println();
    }

}

The error apperas when it gets to the first line in the map, the part where it checks if the selected section contains "X". If it does the problem appears.

4

3 回答 3

4

肯定是

passable[x][y] = twoDMap[y][x].charAt(0) == 'X' ? false : true;

而不是charAt(x)…………

但是,关于代码还有更多要说的......

  1. 不要通过使用Stringwhere a charwould do 来混淆它。
  2. 不要用a == b ? false : true. 简直a != b可以。
  3. 如果像下面这样完成,使用字符串是非常有意义的。

 

String[] twoDMap = {
    { ".....X...." },// ROW0
    { ".XXX.XXX.." },// ROW1
    ...
于 2013-09-23T00:05:40.527 回答
1

您正在测试charAt(x)在您的情况下是否0会抛出此错误。你的String对象都是 1 个字符长,所以你应该这样做.charAt(0)

或者更好的是,只需测试,.equalsIgnoreCase("X")'因为它们都是您要测试的相同字符。

于 2013-09-23T00:05:17.627 回答
1

你在打电话

....charAt(x)其中x最大为 10,即 的长度twoDMap。您的每个字符串只有 1 个字符(索引 0),因此任何大于零的索引总是超出范围。

于 2013-09-23T00:06:16.783 回答