【发布时间】:2018-10-15 19:27:13
【问题描述】:
我正在尝试将 4 个字符从一个方法返回到一个数组,但得到如下所示的错误。到目前为止,我已经尝试在两个位置调用该方法,并在下面将它们注释掉。这样做的正确方法是什么?
class App{
public static void main(String[]args){
App theApp = new App();
}
// position 1 - RandomizeCodeBlock();
char[] charactersAllowed;
char[] charArray;
public App(){
// position 2 - RandomizeCodeBlock();
for(int i=0; i<4; i++){
System.out.println(charArray[i]);
}
}
public char RandomizeCodeBlock()
{
char[] charactersAllowed = {'A','B','C','D','E','F','G'};
charArray = new char[4];
int i;
for(i = 0; i < charArray.length; i++) {
charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
}return charArray[i];
}
}
我收到此错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at App.RandomizeCodeBlock(App.java:33)
at App.<init>(App.java:17)
at App.main(App.java:5)
【问题讨论】:
-
currentCharacters声明在哪里? -
抱歉,println 上的 currentCharacters 应该是 charArray。
标签: java arrays random methods