数组容器不足以容纳所有需要的值

时间:2018-03-18 06:56:54

标签: java arrays

这个程序发现从1开始的斐波那契序列然后将2位数字分开,这样它就不会太大,然后将数字加上因子并加上它们。
我的问题是它缺少序列中的最终值,因为数组不够大,但是如果我改变它就会给我java.lang.ArrayIndexOutOfBoundsException错误(例外)

 int sum = 1;
    int input;

    System.out.print("Enter a number: ");
    input = console.nextInt();

    int[] fib = new int[input];
    int[] out = new int[input];
    int[] fib2 = new int[input];

    fib[0] = 0;
    fib[1] = 1;

    fib2[0] = 0;
    fib2[1] = 1;
    if (input > 0) {

        if (input <= 7) { // for numbers 1,1,2,3,5,8 
            for (int i = 2; i < input; i++) {
                fib[i] = fib[i - 1] + fib[i - 2];
                out[i] = factorial(fib[i]);

            }
        } else { // this is for the 2 digit numbers 13,21,34,55,89
            for (int i = 2; i < input; i++) {
                fib[i] = fib[i - 1] + fib[i - 2];
                fib2[i] = fib2[i - 1] + fib2[i - 2];
            }
            for (int i = 2; i < input; i++) {
                fib[i] = separate(fib[i]);
                fib2[i] = separate2(fib2[i]);
                out[i] = factorial(fib[i]) + factorial(fib2[i]);
            }

        }

        for (int i : out) {
            sum = sum + i;
        }
        System.out.println(sum);
}

输出为40,490,但应该是40,730 一切正常,除非我输入10,否则它缺少最终值55。 计算就像这样!1!+ 1!+2!+3!+5!+8!+1!+3!+2!+ 1!+ 3!+4!+5!+5! = 40,730

1 个答案:

答案 0 :(得分:3)

如果您不确切知道ArrayList将存储多少数据,则应使用Array代替array

ArrayListArray

略有不同

您可以详细了解ArrayList Package.ShowOptionPage

用我的代码替换您给定的代码: -

int sum = 1;
int input;

System.out.print("Enter a number: ");
input = console.nextInt();

ArrayList<Integer> fib = new ArrayList<Integer>();
ArrayList<Integer> out = new ArrayList<Integer>();
ArrayList<Integer> fib2 = new ArrayList<Integer>();

fib.add(0);
fib.add(1);

fib2.add(0);
fib2.add(1);
if (input > 0) {

    if (input <= 7) { // for numbers 1,1,2,3,5,8 
        for (int i = 2; i < input; i++) {
            fib.add(i, fib.get(i - 1) + fib.get(i - 2));
            out.add(i, factorial(fib.get(i)));

        }
    } else { // this is for the 2 digit numbers 13,21,34,55,89
        for (int i = 2; i < input; i++) {
            fib.add(i, fib.get(i - 1) + fib.get(i - 2));
            fib2.add(i, fib2.get(i - 1) + fib2.get(i - 2));
        }
        for (int i = 2; i < input; i++) {
            fib.add(i, separate(fib.get(i)));
            fib2.add(i, separate2(fib2.get(i)));
            out.add(i, factorial(fib.get(i)) + factorial(fib2.get(i)));
        }

    }

    for (int i : out) {
        sum = sum + i;
    }
    System.out.println(sum);
}