数组索引超出范围,值不分配给数组变量

时间:2014-11-16 18:31:13

标签: java arrays

我试图找出给定的数字列表是否在fibonacci系列中,但我得到数组超出范围异常并且没有为fiboSeries分配值。请帮我找出我犯的错误。

import java.io.*;
import java.util.*;

public class Solution {

    private static int MAX_LIMIT = 10000;
    private static int[] fiboSeries = new int[MAX_LIMIT];
    private static int fiboCount;

    Solution(){
        fiboSeries[0]=0;
        fiboSeries[1]=1;
        fiboSeries[2]=1;
        fiboCount = 2;
    }

    public static void main(String[] args) {

        Scanner get = new Scanner(System.in);
        int TC = get.nextInt();
        int[] N = new int[TC];
        boolean[] isFibo = new boolean[TC];

        //getting no and evaluating for fibo
        for(int i = 0;i<TC;i++){
            N[i] = get.nextInt();
            isFibo[i] = isFiboNum(N[i]);
        }

        //printing the results
        for(int i = 0;i<TC;i++){
            if(isFibo[i])
                System.out.println("IsFibo");
            else
                System.out.println("IsNotFibo");
        }
    }
    //function to determine if the number is fibonacci
    static boolean isFiboNum(int n){
        //if n does not lie within the previously calculated range calcuate fibo to extend the range
        if(fiboSeries[fiboCount]<n){
            fiboSeries[fiboCount+1] = fiboSeries[fiboCount] + fiboSeries[fiboCount-1];
            fiboCount++;
            if(fiboSeries[fiboCount]==n)
                return  true;
            else if(fiboSeries[fiboCount] > n)//if the newly calculated fibo num exceeds n, n is not in fibo series
                return false;
            else
                return isFiboNum(n);

        }else{//it lies within the previouly calculated range
            for(int i=fiboCount;i>=0;i--){
                if(fiboSeries[i]==n)
                    return true;
            }
        }
        //if its not in the list return false;
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

if

if(fiboSeries[fiboCount]<n){

应该替换为像

这样的循环
while (fiboSeries[fiboCount] < n) {
  fiboSeries[fiboCount] = fiboSeries[fiboCount-1] + fiboSeries[fiboCount-2];
  fiboCount++;
}

这样您就可以将序列填充到n。然后我建议你从右到左搜索

int i = fiboCount - 1;
while (fiboSeries[i] >= n) {
  if (fiboSeries[i] == n) return true;
  i--;
}
return false;

修改

另外,你的构造函数

Solution(){
    fiboSeries[0]=0;
    fiboSeries[1]=1;
    fiboSeries[2]=1;
    fiboCount = 2;
}

应该是静态初始化块,因为您不使用Solution个实例。

static {
    fiboSeries[0]=0;
    fiboSeries[1]=1;
    fiboSeries[2]=1;
    fiboCount = 2;
}