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++;
    }
    return j;
   }
}
share|improve this question

feedback

4 Answers

up vote 2 down vote accepted

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];        
} 
share|improve this answer
+1 god one it solves the problem.,see my answer also it is an alternative. – Ishu Mar 10 '11 at 5:28
feedback

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;
}
share|improve this answer
feedback

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];

}
share|improve this answer
feedback
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 ?
}
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.