错误:java.lang.IndexOutOfBoundsException:索引70无效,大小为10;
我已经创建了一个函数来创建随机的Integer ArrayList,并用它做一些操作,现在我试图让它适应Chars,我得到了奇怪的错误,因为在我看来,默认的字符数组大小更大然后整数一个,但我不确定。我可以用这个代码做什么?
功能在此处失败:numbers.set(rightNumbers.get(k),answer.charAt(k));
@Override
public void charactersRandomise(String answer) {
final String alphabet = "ABSDEFGHMN";
final int N = alphabet.length();
ArrayList<Character> numbers = new ArrayList<Character>();
ArrayList<Character> rightNumbers = new ArrayList<Character>();
Random randomGenerator = new Random();
int i=0;
Log.d("size",String.valueOf(N));
while (numbers.size() < 10) {
char random = alphabet.charAt(randomGenerator.nextInt(N));
if (!numbers.contains(random)) {
numbers.add(random);
Log.d("numbers", numbers.get(i).toString());
i++;
}
}
int j=0;
while (rightNumbers.size() < answer.length()) {
char random = alphabet.charAt(randomGenerator.nextInt(N));
if (!rightNumbers.contains(random)) {
rightNumbers.add(random);
Log.d("RightNumbers",rightNumbers.get(j).toString());
j++;
}
}
for(int k =0;k<rightNumbers.size();k++){
numbers.set(rightNumbers.get(k),answer.charAt(k));
Log.d(rightNumbers.get(k)+"", numbers.get(rightNumbers.get(k)).toString());
}
for (int h=0;h<numbers.size()-1;h++) {
Log.d("newNumber", String.valueOf(numbers.get(h)));
}
for(int m=0;m<buttons.length;m++){
buttons[m].setText(numbers.get(m) + "");
}
}
答案 0 :(得分:2)
numbers.set(rightNumbers.get(k),answer.charAt(k));
- 此表达式rightNumbers.get(k)
检索一个字符。在ASCII中,这个字符(我可以看到它是F
)被转换为int
中的数字70,这就是异常发生的原因。
将其替换为:
numbers.set(k ,answer.charAt(k));