![](/img/trans.png)
[英]Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
[英]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數組,該數組為rowsnum
和colsnum
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
)。
i
和j
是gridCell[j][i]
(以及其他地方)中錯誤的處理方式,或者rowsnum
和colsnum
是new 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.