簡體   English   中英

線程“ main”中的異常java.lang.ArrayIndexOutOfBoundsException:3

[英]Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3

我正在嘗試在Java中實現A *尋路算法 因此,我創建了一個網格,並要求用戶提供其尺寸。 問題在於,當width!= height時 ,程序將拋出該異常。 例如,創建網格5x5不會出現問題,而不會創建網格5x7。 我不確定該如何解決。 這是代碼:

JFrame frame = new JFrame();
String rows =  JOptionPane.showInputDialog(frame,
                "Συμπληρώστε τον αριθμό γραμμών του πλέγματος: \n",
                "Δημιουργία πλέγματος",
                JOptionPane.PLAIN_MESSAGE);
String cols =  JOptionPane.showInputDialog(frame,
                "Συμπληρώστε τον αριθμό στηλών του πλέγματος: \n",
                "Δημιουργία πλέγματος",
                JOptionPane.PLAIN_MESSAGE);
int rowsnum = Integer.parseInt(rows); 
int colsnum = Integer.parseInt(cols);
transient Image buffer; 

GridCell gridCell[][] = new GridCell[rowsnum][colsnum];
public Map()
{
    super();
    //{{INIT_CONTROLS
    setLayout(new GridLayout(rowsnum,colsnum));
    //}}
    for(int i=0;i<rowsnum;i++){
        for(int j=0;j<colsnum;j++){
            System.out.println ("i=" + i + " j="+ j);
           gridCell[j][i] = new GridCell();
           gridCell[j][i].setPosition(new Point(j,i));
           add(gridCell[j][i]);
        }
    }
}

如您所見,我在每個循環中打印i和j以查看問題出在哪里。 結果是(當我嘗試創建3x5網格時):

run:

i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Map.<init>(Map.java:32)

第32行是:

gridCell[j][i] = new GridCell();

如果有人可以幫助我,我將不勝感激!

附注:忽略希臘! :-D

在此行上,創建一個2D數組,該數組為rowsnumcolsnum

GridCell gridCell[][] = new GridCell[rowsnum][colsnum];

但是在這里,您使用它的方式就好像它是colsnum by rowsnum

for(int i=0;i<rowsnum;i++){
    for(int j=0;j<colsnum;j++){
        System.out.println ("i=" + i + " j="+ j);
       gridCell[j][i] = new GridCell();

i在0和rowsnum之間(不包括),但在0到colsnum之間(不包括)

j介於0和colsnum之間(不包括colsnum ),但位於0到rowsnum之間(不包括rowsnum )。

ijgridCell[j][i] (以及其他地方)中錯誤的處理方式,或者rowsnumcolsnumnew GridCell[rowsnum][colsnum]方式錯誤。 它是哪一個取決於您要實現的目標,盡管通常它通常是數組(行,列); 暗示我和j是錯誤的方法

問題在於代碼中使用行索引(i)和col injex(j)的方式。 請在以下代碼中交換i和j

       gridCell[j][i] = new GridCell();
       gridCell[j][i].setPosition(new Point(j,i));
       add(gridCell[j][i]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM