1

I know a similar question has been asked and I have researched this website. I have tried to use some of the answers but my syntax is still not working.

I am going through a previous examination paper to help build my knowledge of Java. Please forgive any errors in my code, I am still learning the Java syntax.

Here is my question:

Implement a method static int[] splice(int[] v, int[] w) that (assuming the lengths of v and w are the same) returns an array in which the elements if v and w are interleaved, starting with the first element of v, followed by the first element of w, followed by the second element of v, etc. For example, if v = { 1, 3, 5 } and w = { 2, 4, 6 } the call splice should return { 1, 2, 3, 4, 5, 6 }.

If the input arrays have different lengths, the method should return null.

Here is my code:

import java.util.*;

public class TwoArraysBecomeOne {

public static void main(String[] args) {

    int[] v = { 1, 3, 5 };
    int[] w = { 2, 4, 6 };

    splice(v,w);
}

public static int[] splice(int[] v, int[] w){

    if(v != w) {
        return null;
    }

    int[] x = new int[v.length + w.length];

    for (int i = 0; i < v.length; i++) {
        x[i] = v[i] + w[i];
    }

    for (int j = 0; j < x.length; j++) {
        System.out.println(x[j]);
    }

    return x;

    }
}

I am aware that my current syntax is producing a new array x = { 3, 7, 11 }. I have removed the various attempts to try and concatenate my code as this was causing errors in my code. I just require some pointers to help answer this question.

Again, please forgive any errors in my code, I am still learning Java.

Thank you.

4

2 回答 2

2

您只是有一个小错误,您不想对数组的元素求和,而是将它们并排放置在新数组中

for (int i = 0; i < v.length; i++) {
    x[i*2] = v[i];
    x[i*2+1] = w[i];
}
于 2013-05-13T21:12:36.607 回答
2

尝试这个

public static void main(String[] args) throws Exception {
    int[] v = { 1, 3, 5 };
    int[] w = { 2, 4, 6 };
    int[] res = splice(v, w);
    System.out.println(Arrays.toString(res));
}

private static int[] splice(int[] v, int[] w) {
    if (v.length != w.length) {
        return null;
    }
    int[] a = new int[v.length + w.length];
    for (int i = 0; i < v.length; i++) {
        a[i * 2] = v[i];
        a[i * 2 + 1] = w[i];
    }
    return a;
}

输出

[1, 2, 3, 4, 5, 6]
于 2013-05-13T21:17:47.093 回答