java - 异常线程 "main"java.lang.ArrayIndexOutOfBoundsException : 1000000 at problem2. main(problem2.java:17)

标签 java arrays indexoutofboundsexception

我收到以下错误,我不知道为什么。我尝试查找它,但没有找到解决方案。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)

这是我的代码:

//Each new term in the Fibonacci sequence is generated by adding the previous two terms.
//By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//By considering the terms in the Fibonacci sequence whose values do not exceed four million, 
//find the sum of the even-valued terms.

public class problem2 {
    public static void main(String[] args) {
        int []a = new int[1000000];
        a[0] = 1;
        a[1] = 2;
        int sum=0;

        int i=2;
        while(a[i]<=4000000){
            a[i] = a[i-1] + a[i-2];
            i++;
        }

        for(int j=0;j<i;j++){
            sum = sum + a[j];
        }

        System.out.println("The sum is: " + sum);
        System.out.println("\nThere are " + i + " numbers in the sequence.\n");
        System.out.println("This are all the numbers in the sequence:");

        for(int j=0;j<i;j++){
            if(j+1==i){
                System.out.print(a[j] + ".");
                break;
            }

            System.out.print(a[j] + ", ");
        }
    }
}

最佳答案

问题不在于 int[] 的大小。

您的 while 循环不断地检查 a[i] 是否小于 4000000i 变量已经是前面的一个索引。每个循环都有 a[i] == 0

此更改将为您修复代码:

int i=1;
while(a[i]<=4000000){
    i++;
    a[i] = a[i-1] + a[i-2];
}

关于java - 异常线程 "main"java.lang.ArrayIndexOutOfBoundsException : 1000000 at problem2. main(problem2.java:17),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12005323/

相关文章:

java - 如何避免执行幂等代码?

javascript - 如何按时间戳对javascript对象进行反向排序

java - BitSet(JAVA) 在埃拉托斯特尼筛法的实现中抛出 outofBoundsException

java - 您可以启动一个 Activity 作为其自身的实例吗?

java - LinkedHashSet 和 subList,获取集合的 n

java - 如何创建 JSP 页面和共享数据库连接

iOS swift : Track and store indices of all duplicate values in an array?

iphone - 数组,找到有值的对象并获取其indexPath

java - 在 jtext 区域中打印 unicode 字词时出现 ArrayIndexOutofBoundException。 (马拉雅拉姆语词)

java - 为什么我会遇到索引越界异常?