开发者

Need help solving issue with Java array problem

I need a little help. I'm trying to put together a small Java program that creates and returns an array containing all elements of a, each of these duplicated. However, every time I try to execute my code I get an "out of bounds" exception. Please give me an idea of where I'm going wrong. Thanks! Here is what I have so far:

public class integerStutter
{
    public static int[] stutter(int [] a){
       int[] j = new int[a.length*2];

        for(int i=0; i < j.length; i++){

            j[i] = a[i];
            j[i+1] = a[i];
            i++;
 开发者_Python百科   }
    return j;
   }
}


The old and new array are not of equal sizes. You are trying to access elements from old array using valid indices for the new array (which is of double size) and this is causing the exception.

Instead try:

// iterate over the old array.
for(int i=0; i < a.length; i++){

        // index into new array.
        int x = 2 * i;

        // copy old array ele at index i into new array at index x and x+1.
        j[x] = j[x+1] = a[i];        
} 


int[] j = new int[a.length*2];

So, the size of arrays j, a are not equal. But the loop runs until j.length -

for(int i=0; i < j.length; i++){

     j[i] = a[i];    // array out of bounds once i passes a.length
     j[i+1] = a[i];  // array out of bounds once i passes a.length
     i++;  // Why again incrementing here ?
}


you can do it like this

for(int i=0,k=0;i<a.length;i++,k=k+2)
{
     j[k]=j[k+1]=a[i];

}


If I understand the question correctly, this will do what you need. It is also a nice clean solution.

public static int[] stutter(int[] a) {
    int[] j = new int[a.length * 2];

    for (int i = 0; i < a.length; i++) {
        j[i * 2] = a[i];
        j[i * 2 + 1] = a[i];
    }

    return j;
}


public class integerStutter
{
public static int[] stutter(int [] a){
    int[] j = new int[a.length*2];

    for(int i=0; i < j.length; i++){

        j[i] = a[i];
        j[i+1] = a[i];
        i++;
    }
    return j;
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜