我收到以下错误,我不知道为什么。我尝试查找它,但我没有找到解决方案。
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1000000 at question2.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] + ", ");
}
}
}