java - 数组索引越界错误

标签 java arrays

由于某种原因,我收到此错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Assignment25.main(Assignment25.java:80)

public static void main (String[] args){
long[] array = new long[7];
for (int i = 0; i < 6; i++){
    int thefib = 39;
    array[i] = fib(thefib);
    thefib++;
}

int counter = 0;
int counter1 = 1;
for(int i = 0; i < 6; i++){
    long start = System.currentTimeMillis();
    gcd(array[counter], array[counter1]);
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("GCD time for " + (counter + 39) + " and " + (counter1 + 
        39) + " is " + time);
    counter++;
    counter1++;
}

counter = 0;
counter = 1;
for(int i = 0; i < 6; i++){
    long start1 = System.currentTimeMillis();
    gcd2(array[counter], array[counter1]);
    long end1 = System.currentTimeMillis();
    long time1 = end1 - start1;
    System.out.println("GCD2 time for " + (counter + 39) + " and " + (counter1 + 
        39) + " is " + time1);
    counter++;
    counter1++;
    }
}

}

最佳答案

由于您从 1 启动 counter1 以及 for 循环进行 6 迭代, counter1 在最后一次迭代中变为 7,从而产生 ArrayIndexOutOfBoundsException。因为 array 的大小为 7,并且当 counter1< 时,您尝试使用 array[counter1] 访问索引 7/code> 变为 7。

数组中的最大可访问索引始终为array.length - 1,在您的情况下,array[6]是数组的最后一个可访问索引。

关于java - 数组索引越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198076/

相关文章:

java - 从现有的 MySQL 数据库生成简单的 JAVA CRUD 类

Java - addDigits 方法的大O?

Java正则表达式用于对特定模式进行正数和少数特殊符号验证

javascript - 如何通过值比较合并两个数组 - Google Analytics 和 MongoDB

java - 无法发现程序中的空异常

java - 关于如何为 Hbase 编写 Hadoop InputFormat/OutputFormat 的任何想法

java - 使用instanceof 运算符可以比较对象的什么?

javascript - Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?

c++ - '->' token 之前预期有不合格的 id,如何解决此问题?

Java:将数组减少到特定数量的平均值