1

I need to merge two different arrays into one. I have to call the two arrays in a method as parameters and the both should be merged inside a for loop. Can anyone help me with this? This is the coding I have so far, but the program always has this output : " Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4"

public class rest {

  public static void main(String[] args) {
        int[] a= {1,4,8,12};
        int[] b= {21,44,78,132,144};
        int[] c= {-5,-4,-3,-2,-1,0};
        int[] d;

    d = combine(a, b);
    print(d);
    d = combine(a, c);
    print(d);
    d = combine(null, c);
    print(d);
  }
  static int[] combine(int[] a, int[] b) {
    if (a.length <= 0 || b.length <= 0) return null;

    int[] combined = new int[a.length + b.length];
    int j = 0;
    for (int i = 0; i < combined.length; i++) {
      if (i <= a.length) {
        combined[i] = a[i];
      } else {
        combined[i] = b[j];
        j++;
      }
    }
    return combined;
  }
  static String print(int[] a) {
    for (int i = 0; i < a.length; i++) {
      System.out.print(a[i]);
    }
    return " ";
  }
}

0 Answers0