java - IndexOutOfBounds,当它不应该的时候

标签 java

我正在学习Java语言,我正在尝试制作MasterMind游戏。 我在尝试编译时收到以下错误,在尝试调试代码后,我找不到错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 97, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.remove(ArrayList.java:474)
    at mastermind.Combinacion.aciertos(Combinacion.java:115)
    at mastermind.Combinacion.principal(Combinacion.java:36)
    at mastermind.MasterMind.main(MasterMind.java:21)
Java Result: 1

下面的代码是“aciertos”方法,给定一个 key 和一个组合,告诉您 key 中有多少个字母。

    public int aciertos(Combinacion comb){
    int aciert = 0;
    List<Character> clave = new ArrayList();
    // Transform the key to a List, so we can easily check what contains and remove elements
    for(char c : this.codigo){
        clave.add(c);
    }
    // We go though the user try, and we check if the letter it is in the secret key list. If it is, we remove it from the list, to avoid counting twice if the user has a letter repeated and it is only once in the secret key.
    for (int i = 0; i < comb.codigo.length; i++) {
        if(clave.contains(comb.codigo[i])){
            aciert++;
            clave.remove(comb.codigo[i]);
        }
    }
    return aciert;
}

这些是 Combinacion 类中的字段:

//Size of each combination
private int tamano = 4;
//Los valores válidos son: blanco, negro, azul, rojo, verde, marron
private static Character[] valoresValidos = {'b', 'n', 'a', 'r', 'v', 'm'};
private static List<Character> valores = Arrays.asList(valoresValidos);
private char[] codigo = new char[tamano];

P.D:我应该开始用英语写作和评论所有内容,对西类牙语单词感到抱歉。

最佳答案

该错误在第一行表示您正在尝试读取只有 4 个元素的 ArrayList 中的索引 97。 ArrayList.remove() 使用索引作为参数,而不是要删除的对象:

clave.remove(comb.codigo[i])

必须替换为:

clave.remove(clave.indexOf(comb.codigo[i]))

关于java - IndexOutOfBounds,当它不应该的时候,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425801/

相关文章:

java - 如何使用 mvn -D 通过命令行在 Maven 中设置(多个)属性?

java - Label 的 labelFor 字段未按预期运行

java - 异常 : java. lang.IllegalArgumentException:切入点格式不正确:期望 ')'

java - Java 的 PriorityQueue 与最小堆有何不同?

java - 在 Apache HttpClient 中设置自定义文件名

java - 删除 EditText 中的第二个点/逗号

java - 尽管我的 cucumber 测试运行良好并检测到步骤,为什么我的 .feature 文件显示 "Undefined step reference"?

java - derby 数据库在 where 条件下的问题

java.reflection.Method.invoke(...) 不重新转换参数

java - 与 Java 同步异步 API 调用