我编写的这段代码遇到了一些问题,因为我收到了 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;
}
}
非常感谢!
最佳答案
正如错误所示,这是由于访问超出了数组范围。 IE。数组上的一些错误索引访问。
char[] store = new char[k - 1];
您正在创建一个大小为 k-1
的store
字符数组
并将 k
作为大小传递给 charN()
charN(numStore, store, k);
解决您的问题。 更改商店声明如下
char[] store = new char[k];
此外,在类测试
中,k
必须为3
,而不是2。其中k是数组的大小。
static int k = 3;
当数组的大小为k时,数组的索引从0
到k-1
关于java - 数组索引越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14634271/