计算二维数组中元素的数量,然后创建新数组

时间:2017-11-12 15:07:20

标签: java arrays count integer

我有这个数组:

  

int a [] [] = {{1,2,3},{4,5,6},{6,3},{8},{7}};

我想打印最多3行的新照片: {1,2,3},{4,5,6},{6,3}

                public static int[][] cut(int arr[][], int n) {
        // n : is up " up to which row ? " Here is n = 3
            // FIRST STEP : 
            //  COUNTING ELEMENTS 
                        int counter = 0;
                        for (int row = 0; row < arr.length; row++) {
                            for (int column = 0; column < arr[row].length; column++) {
                                counter++;
                            }
                            System.out.println(counter);
                            counter = 0;
                        }
            // PRINTS 3   3   2  1  1 : OK 

            // SECOND STEP : I only want up to 3 row so : 3   3     2
            // CREATE AN EMPTY TWO DIMENSIONAL ARRAY but how ? 
     //I think that I should be using a loop for but I've no idea how   
                            int be[][] = new int[n][];

                        for ( int i = 0; i < n ; i ++){
                       be[i][counter]; 
                       // This doesn't work, I know why but I don't have other suggestion :s 

    }

// THIRD STEP : Putting values in the new array 


                            }
                            return be;  
                    }

谢谢

2 个答案:

答案 0 :(得分:0)

将二维数组的一维数组逐个分配给另一个二维数组。

演示 - http://ide.geeksforgeeks.org/306eYp

答案 1 :(得分:0)

为了定义二维数组,你应该修改for循环

for ( int i = 0; i < n ; i ++){
  be[i] = new int[arr[i].lenght];
}