二维数组中的ArrayIndexOutOfBoundsException

时间:2016-04-11 21:38:01

标签: java arrays multidimensional-array

当我尝试将rowNum = 2和colNum = 2传递到2d数组时,我得到一个异常,它应该返回false,有人可以帮我这个吗?

    public boolean addPassenger(String passName, int rowNum, int colNum) {
    boolean check = false;
     System.out.println("row num: " + rowNum + " column num: " + colNum);
     System.out.println("row length: " + p.length + " column length: " + p[0].length);

    if (rowNum <= p.length && colNum <= p[0].length && rowNum >= 0 && colNum >= 0 && p[rowNum][colNum].getName().equals("")) {

        p[rowNum][colNum] = new Passenger(passName, f);
        check = true;

    } else if (rowNum >= p.length || colNum >= p[0].length || !p[rowNum][colNum].getName().equals("")) {

        check = false;
    } else {
        check = false;
    }

    return check;
}

这是一些输出

              run:
        Welcome to blank Airlines
        Enter a flight number:
        R62
        Enter the number of rows:
        2
        Enter the number of seats per row:
        2
        Enter add, remove, seats, list, or quit:
        add
        Enter passenger name, row, and seat:
        me 0 0
        row num: 0 column num: 0
        row length: 2 column length: 2
        Passenger me was added.
        Enter add, remove, seats, list, or quit:
        seats
         |         0||         1|
        0|        me||          |
        1|          ||          |
        Enter add, remove, seats, list, or quit:
        add
        Enter passenger name, row, and seat:
        you 2 2
        row num: 2 column num: 2
        row length: 2 column length: 2
        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
                at csc212hw06.Plane.addPassenger(Plane.java:34)
                at csc212hw06.Main.main(Main.java:61)
        Java Result: 1

这是例外

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at csc212hw06.Plane.addPassenger(Plane.java:34)
at csc212hw06.Main.main(Main.java:61)
Java Result: 1

如果有人有任何建议,将非常感谢!

1 个答案:

答案 0 :(得分:0)

if (rowNum <= p.length && colNum <= p[0].length && rowNum >= 0 && colNum >= 0 && p[rowNum][colNum].getName().equals("")) {

应该是rowNum < p.length && colNum < p[0].length,而不是rowNum <= p.length && colNum <= p[0].length。在n大小的数组中,有效索引为[0,n-1],这意味着索引n将提供越界错误。