[英]Array index out of bounds Error
我編寫的這段代碼遇到了一些麻煩,因為遇到了ArrayIndexOutofBounds
異常錯誤,我不知道發生了什么。 我希望我的代碼產生的是一個char型數字數組。
這是代碼:
public class testing {
static int k = 2;
public static void main(String args[]) {
int[] numArr = new int[] { 15, 18, 21 };
createChar(numArr, k);
}
public static char[] createChar(int numArr[], int k) {
char[] store = new char[k - 1];
for (int i = 0; i < k; i++) {
int divide = numArr[i] / 4;
int numStore = divide % 4;
charN(numStore, store, k);
}
return store;
}
public static char[] charN(int numStore, char store[], int k) {
for (int i = 0; i < k; i++) {
if (k == 0) {
} else {
store[k - 1] = (char) numStore;
k = k - 1;
}
}
System.out.print(store);
return store;
}
}
非常感謝!
正如錯誤所暗示的,這是由於訪問超出了數組的邊界。 即。 數組上的一些錯誤的索引訪問。
char[] store = new char[k - 1];
您正在創建大小為k-1
的store
字符數組
並將k
作為大小傳遞給charN()
charN(numStore, store, k);
解決您的問題。 如下更改商店聲明
char[] store = new char[k];
另外,在class Testing
, k
必須為3
,而不是2。其中k是數組的大小。
static int k = 3;
當數組的大小為k時,數組的索引從0
到k-1
對於值k = 2
,以下語句:-
char[] store = new char[k - 1];
創建一個大小為1
的數組。 因此,您只能訪問其0th index
。
但是,進一步在charN
方法中,您將在以下位置訪問它的1st
索引:-
store[k - 1] = (char) numStore; // Since k = 2, k - 1 = 1.
將數組創建更改為:-
char[] store = new char[k];
此外,我不明白為什么您將k = 2
放在首位。 可能是您打算將其用作index
,在這種情況下,數組創建的大小將為k + 1
。 因此,您的for循環將迭代到k + 1
,而不是k
。
另外,我不了解您的charN
方法的作用。 實際上,tt似乎很奇怪,首先您要在createChar
方法中遍歷數組,然后將每個元素傳遞給charN
方法。 然后,您還要遍歷char array
,將相同的值分配給多個索引。 除此之外,您在循環中同時減少k
和增加i
。 真的很奇怪 最后,您從兩個方法都返回了array
,但根本沒有使用返回值。
很難理解您想做什么。 但是您應該考慮我在上一段中所說的所有要點。 考慮到那里的每個步驟,為什么要這樣做? 有沒有其他選擇可能很容易? 是的,我真的需要在這里進行2次迭代的方法嗎?
我建議您再次看一下您的設計。 我上面發布的解決方案可能會解決您的compiler error
,但是您的logic
存在一些問題。 您需要注意這一點。
根據您的帖子聲明
char[] store = new char[k - 1];
導致大小為1的char數組。因此,當您嘗試訪問
store[k - 1] = (char) numStore;
您正在嘗試訪問store [1],因為此處的“ k”為2。 哪有錯 因為使用store [1]您試圖訪問數組中的第二個元素,其中數組大小僅為1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.