2016-04-11 13 views
-1

rowNum = 2とcolNum = 2を2次元配列に渡そうとすると、falseを返すべきときに例外が発生します。誰かがこれを手助けできますか?ここでArrayIndexOutOfBoundsException 2d配列

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

基本的に私たちにあなたに求めているものであるデバッガを使用してください。 – redFIVE

+1

'rowNum <= p.length'をチェックして' p [rowNum] 'にアクセスしてください。 ( 'colNum'と同様に) –

答えて

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は範囲外のエラーを出力します。

+0

すごくうれしかった – Demuze28