数组中的异常错误

时间:2016-03-07 22:23:49

标签: java arrays

我的代码用于获取一个int数组,并返回一个int数组,其长度是原始数组长度的两倍,减去2.

返回的数组在原始数组中任何给定的两个值之间应具有值 1/3和2/3

例如输入数组:

  

{400,500,600}

将返回:

  

{400,433,466,500,533,566,600}

我的代码如下:

public static void main(String[] args){
            System.out.println("Problem 9 tests");
            int[] arr7={300, 400, 500};
            System.out.println(highDef(arr7));
            System.out.println(" ");

public static int[] highDef(int[] original) {
        int[] newarr = new int[original.length*3-2];
        newarr[0]=original[0];
        int count=0;
        while (count!=newarr.length) {
                int increment=(original[count+1]-original[count])/3;
                newarr[count+1]=original[count]+increment;
                newarr[count+2]=original[count]+(count*increment);
                count+=1;
        }
        return newarr;

2 个答案:

答案 0 :(得分:1)

第一次看起来不够好:) 你走了:

public static void main(String[] args) {
    System.out.println("Problem 9 tests");
    int[] arr7 = {300, 400, 500};
    System.out.println(Arrays.toString(highDef(arr7)));
    System.out.println(" ");
}

public static int[] highDef(int[] original) {
    int[] newarr = new int[original.length * 3 - 2];
    newarr[original.length * 3 - 3] = original[original.length-1];

    for(int i=0; i<original.length-1; i++){
        newarr[i*3] = original[i];
        int increment = (original[i+1] - original[i])/3;
        newarr[i*3+1] = original[i] + increment;
        newarr[i*3+2] = original[i] + increment*2;
    }

    return newarr;
}

答案 1 :(得分:0)

使用数组超出范围的异常,尝试考虑最后一种情况。

在你的例子中:

original.length = 3

newarr.length =(original.length * 3) - 2 = 7

while (count!=newarr.length) // this means: while count does not equal to 7. Therefore *Count* value can go upto 6
// imagine the last case, count = 6
newarr[count+2]=original[count]+(count*increment); // the problem is here
// count(6) + 2 = 8, which is out of bounds

此行的同一问题:int increment=(original[count+1]-original[count])/3;

计数最多为6,但original[count+1] = original[7]也会超出范围