2011-07-19 116 views
-1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 

我有布爾類型 是爲什麼我會收到一個ArrayIndexOutOfBoundsException?

static boolean[][] a = new boolean[50][50]; 

每次獲取輸入, 它標誌着指定的數組爲真 即陣列,

for(int i=0; i<k; i++){ 
    int x=sc.nextInt(); 
    int y=sc.nextInt(); 
    a[x][y] = true; 
} 

但是當數輸入,根據K,變大, 以下錯誤出來

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 

什麼不對這個

+3

什麼是sc.nextInt()? – Kal

+0

請更改您的問題標題。 :) – everton

+2

K的價值是什麼? – slandau

回答

5

Exception你看到的是因爲你試圖訪問不存在(外位於數組的元素邊界)。

您初始化的數組在兩個維中都有元素0 ... 49。所以,你可以將值插入深藏在一個[0-49]任意位置[0-49]

當你這樣做:

int x=sc.nextInt(); 
int y=sc.nextInt(); 
a[x][y] = true; 

有您訪問超出這些位置的值possibliity。如負值或太高(在這種情況下,您正在訪問-1)。

您的問題源於sc.nextInt()無法從您的輸入中產生可用整數的事實。你是如何初始化sc

0

xy是-1螞蟻這是無效的數組索引(您的陣列被索引爲0到49)。

3

這意味着你已經試過用數組中的索引-1訪問元素的元素。所以nextInt()返回-1某處。

1

A java.lang.ArrayIndexOutOfBoundsExceptio表示您嘗試訪問陣列中的非法索引。

index < 0index >= array.length

在這種情況下,指數是-1

在您的二維數組中,在某個點上,xy指向頂部數組或嵌套數組中的非法點。

要解決該問題,您可以確保xy始終處於範圍內(可以是bandaid)或修復sc.nextInt()以返回有效值。

for (int i=0; i<k; i++) { 
    int x=sc.nextInt(); 
    int y=sc.nextInt(); 
    if (x<0 || x>=a.length) continue; 
    if (y<0 || y>=a[x].length) continue; 
    a[x][y] = true; 
} 
0

異常線程 「main」 java.lang.ArrayIndexOutOfBoundsException:-1

說,你是試圖訪問指數= -1,數組索引從0

1

開始嘗試在a[x][y] = true; x或y之前打印x和y x或y可能爲-1

0

ArrayIndexOutOfBoundsException的原因是在中x或y大於等於(或低於0)。你必須確保x和y至少爲0,並在最後49

1

嘗試:

for(int i=0; i<a.length; i++){ 
    int x=sc.nextInt(); 
    int y=sc.nextInt(); 
if(x >0 && y>0 && x<a.length && y <a[x].length) 
    a[x][y] = true; 
} 
+1

問題的根源在於輸入,而不是如何處理。在這種情況下,掃描程序應該避免超出數組邊界的值。 – rtheunissen

0

要訪問的數組超出[50] [50]的索引。嘗試在nextInts中指定邊界以將索引保持在範圍內:int x = sc.nextInt(49); int y = sc.nextInt(49);

0

您的掃描儀讀取x和y的值,並且如果其中一個超出了數組的邊界(在本例中小於0且大於49 ),你會得到一個IndexOutOfBoundsException。

相關問題