1

I made a method converting a 2D array into a 1D array but I'm having troubling printing it. There's a problem with making a new array in the main method or calling the method. anyone can help??

public class flatten {

public static int[] flatten1(int[][] a){
    int c=0;
    for(int i=0;i<a.length;i++){
        for(int j=0;j<a[i].length;j++){
            c++;
        }   
    }

    int[] x = new int[c];
    int k=0;

    for(int i=0;i<a.length;i++){
        for(int j=0;j<a[i].length;j++){
            x[k++]=a[i][j];
        }
}
    return x;
}
public static void main(String[]args){
    flatten1 f = new flatten1({{2,5,3,7,4,8},{3,4,1,2}});
    for(int i=0; i<f.length;i++){

        System.out.print(f[i]+" ");
    }

}

}

3 Answers 3

1

Firstly you cannot do this:

   flatten1 f = new flatten1({{2,5,3,7,4,8},{3,4,1,2}});

flatten1 is not a class it is a method, you cannot instantiate flatten1 and input a 2D int array. For the above to legal, you would need to create a class called flatten1 and create a constructor which takes a 2D int array as a parameter and I believe that is not what you want to do.


Your flatten method works perfectly fine, change your main method to the following:

public static void main(String[] args){
   int[][] arrayToBeFlattened = {{2,5,3,7,4,8},{3,4,1,2}};
   int[] oneD = flatten1(arrayToBeFlattened);

   for(int i=0; i<oneD.length;i++){
      System.out.print(oneD[i]+" ");
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

public class flatten {

    public static int[] flatten1(int[][] a) {
        int c = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                c++;
            }
        }

        int[] x = new int[c];
        int k = 0;

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                x[k++] = a[i][j];
            }
        }
        return x;
    }

    public static void main(String[] args) {
        int[][] test_arr = { { 1, 2, 3 }, { 4, 5, 6 } };

        int[] f = flatten.flatten1(test_arr);
        for (int i = 0; i < f.length; i++) {

            System.out.print(f[i] + " ");
        }

    }
}

Comments

0

In your main method, when you print f[i] you're not printing the first value. Since f is an array of arrays you're trying to print the ith array not the i'th element. Make sure you understand this distinction because it's important. Printing the ith array will simply give you its memory address.

To fix this, simply change your print statement to:

System.out.print(Arrays.toString(f[i])+" ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.