有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

二维数组中的java ArrayIndexOutOfBoundsException

当我试图将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) 个答案

  1. # 1 楼答案

    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将给出越界错误