0

这段代码有什么问题?

public class HelloWorld {

        public static void main(String[] args) {
                int[] a={4,3,2,5,1,8,6,7};
                System.out.println(Arrays.toString(HelloWorld.split_array(a)[0])); //expect 4325 here
        } 


    public static int[][] split_array(int[] a){
            int [][] result={};
            int mid = (int) (a.length)/2;
            result[0] = Arrays.copyOfRange(a, 0, mid);
            result[1] = Arrays.copyOfRange(a, mid, a.length);
            return result;
        }

    }
4

3 回答 3

4

You have declared an array with size zero like this:

int [][] result={};

You're trying to access the first and second element of it like this:

result[0] = Arrays.copyOfRange(a, 0, mid);
result[1] = Arrays.copyOfRange(a, mid, a.length);

...but they aren't there because the size is zero.

于 2012-09-22T05:48:48.673 回答
3

您已初始化result为一个空数组。Java 中的数组不会像脚本语言那样自动增长。相反,您需要将它们分配到正确的大小。在这种情况下,您需要执行以下操作:

int [][] result = new int[2][];

这将创建一个大小为 2 的 int 数组的新数组,然后您可以按预期分配数组。

于 2012-09-22T05:50:15.647 回答
1

问题不在于,Arrays.copyOfRange(a, 0, mid);而是在于result[0],因为您尚未初始化数组。`

这是工作代码:

public class Test {
public static void main(String[] args) {
        Test h = new Test();
        int[] a = { 4, 3, 2, 5, 1, 8, 6, 7 };
        System.out.println(Arrays.toString(h.split_array(a)[0])); // expect 4325
                                                                    // here
    }
    public int[][] split_array(int[] a) {
        int[][] result = new int[2][];
        int mid = (int) (a.length) / 2;
        result[0] = Arrays.copyOfRange(a, 0, mid);
        result[1] = Arrays.copyOfRange(a, mid, a.length);
        return result;
    }

}
于 2012-09-22T05:53:17.313 回答