2011-09-18 132 views
0

當我在java中聲明一個數組時,運行時出現此錯誤:線程「main」java.lang.ArrayIndexOutOfBoundsException中的異常。儘管變量totalNumbers有一個值。當我將這個變量替換成一個像5這樣的數字時,它正在工作。當聲明數組時它必須是一個數字嗎?在java中聲明數組

int randomNumbers[]; 
randomNumbers = new int[totalNumbers]; 

增加了一些代碼,但變量名稱和註釋在瑞典!但是,儘管如此,代碼可能會被忽略!或者爲什麼不學一些瑞典語!= :)

// deklarera arrays för tal under 500 och för tal över 500 
int slumptalMindre[]; 
slumptalMindre = new int[antalSlumptalMindreÄn500]; 

int slumptalStörre[]; 
slumptalStörre = new int[antalSlumptal - antalSlumptalMindreÄn500]; 

//gå genom första array och omplacera tal till ny array 
for(int x = 0; x < antalSlumptal; x++) { 
    if(slumptal[x] < 500) { 

     slumptalMindre[x] = slumptal[x]; 
    } 

} 
+2

確定這是整個代碼嗎?嘗試訪問陣列範圍之外的成員時,您會遇到索引越界異常... –

+1

請發佈可編譯代碼和堆棧跟蹤。 ArrayIndexOutOfBoundsException在數組訪問上拋出,但是你沒有發佈代碼數組,只有在初始化的地方 –

+0

不,這不是所有的代碼。我只是問是否可以使用變量而不是數字? –

回答

0

你沒有張貼什麼值可能antalSlumptalMindreÄn500antalSlumptal,但根據您的代碼,我認爲都是積極和antalSlumptal>antalSlumptalMindreÄn500

I.e.讓antalSlumptal = 20和antalSlumptalMindrenn = 5。

然後,數組slumptalMindre的長度是5,slumptalStörre的長度是15.但是沒有聲明數組slumptal

在您的for循環變量x範圍從0到19,並且在每次迭代中您訪問索引爲x的數組slumptalMindre。顯然,當x值變爲5時,會導致ArrayIndexOutOfBoundsException。

我只能猜測你的意圖是什麼。看起來你想在數組slumptal上應用一些過濾器,並將所有小於500的值放入另一個數組中。

使用數組作爲過濾器結果的一個問題是,在循環完成後,您不知道結果的長度。但是你必須事先初始化數組。

所以一個解決方案可能是使用兩個循環。第一次遍歷數組並計算有多少個數小於500.然後,用正確的大小初始化數組,然後第二個循環再次遍歷數組,並將結果值複製到結果數組中。在第二循環中,你必須當心以訪問陣列slumptal索引和索引之間進行區分來訪問較短結果數組:

// count the numbers less than 500 
int count = 0; 
for(int x = 0; x < slumptal.length; x++) { 
    if(slumptal[x] < 500) 
    count++; 
} 
slumptalMindre = new int[count]; 

int y = 0; // Index to access array slumptalMindre 
for(int x = 0; x < slumptal.length; x++) { 
    if(slumptal[x] < 500) 
    slumptalMindre[y++] = slumptal[x]; 
}  

但上述方案不是最佳的,因爲你必須通過陣列進行迭代兩次。這只是因爲結果應該是一個固定長度的數組。這是比較容易在這種情況下,使用像List動態大小的數據結構:關於編碼風格

// Using a ArrayList of Integer values as the result 
List<Integer> slumptalMindre = new ArrayList<Integer>(); 

for(int x = 0; x < slumptal.length; x++) { 
    if(slumptal[x] < 500) 
    slumptalMindre.add(slumptal[x]); 
}  

還有一個提示:這是有效的,在Java變量和類名來使用日爾曼。但是這樣做被認爲是不好的風格,因爲你很容易遇到問題。 Java編譯器使用源文件的平臺默認編碼,除非您指定-encoding選項。在Windows上,默認編碼是Cp1252,在Linux上通常是UTF-8。如果變音屬於類名的一部分,情況會變得更糟,因爲這會導致包含變音節點的類文件名。