0

だから私はいくつかの地図の経路探索を行っていますが、エラーが発生し続けます

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

しかし、それがどのように範囲外になるかはわかりません。マップは 10,10 であるため、x&y 配列部分は 0 ~ 9 になります。

これは私のコードです

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();
    }

}

マップの最初の行、選択されたセクションに「X」が含まれているかどうかをチェックする部分に到達すると、エラーが表示されます。そうであれば、問題が発生します。

4

3 に答える 3

4

It must be

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

rather than ...charAt(x)....

However, there's more to be said about the code....

  1. Don't obfuscate it by using String where a char would do.
  2. Don't obfuscate it by expressions like a == b ? false : true. Simply a != b would do.
  3. Using strings makes perfect sense if done like below.

 

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

You are testing for charAt(x) which in your case if it is ever anything other than 0 will throw this error. Your String objects are all 1 character long, so you should do .charAt(0).

Or better yet, just test for .equalsIgnoreCase("X")' since all of them are the same character that you want to test for.

于 2013-09-23T00:05:17.627 に答える
1

You are calling

....charAt(x) where x is up to 10, the length of the twoDMap. Each of your strings only has 1 character (index 0), so any index greater than zero is always out of bounds.

于 2013-09-23T00:06:16.783 に答える