hello programmers

is it possible to extract some part of 2D array and make a new 1D array?
for example from this array

String[][] twoDarray= {
{"s", "y", "r"},
{"s", "n", "r"},
{"w", "y", "r"},
{"r", "y", "p"}};

take first column of twoDarray[0] and make this arrayString[] newArray = {"s","s","w","r"}; ?

Edited 3 Years Ago by Nick Evan: Fixed formatting

Yes, you've just described how to do it:

take first column of twoDarray[0] and make this array
String[] newArray = {"s","s","w","r"};

Yes, you've just described how to do it:

but how to save these elements into the new array variable?

Okay, start with the easy part, and then we'll do the other easy part. Show me the code that you'd use to print them to the screen.

Okay, start with the easy part, and then we'll do the other easy part. Show me the code that you'd use to print them to the screen.

public class testing {

    static String[][] oldArray= {
            {"s", "y", "r"},
            {"s", "n", "r"},
            {"w", "y", "r"},
            {"r", "y", "p"},
            {"r", "n", "r"},
            {"r", "y", "p"},
            {"w", "n", "p"},
            {"w", "n", "r"},
            {"w", "y", "r"},
            {"s", "n", "r"}};

    static String[] newArray;

    
    public static void main(String args[]){

        System.out.print("new array is: ");
        for(int i = 0; i<oldArray.length; i++){
             System.out.print(oldArray[i][0]);
        }
    }
}

is this correct?

Edited 5 Years Ago by gingerfish: n/a

Looks good to me. Now, suppose I gave you that, and told you to put it into an array of Strings, what would you do?

Looks good to me. Now, suppose I gave you that, and told you to put it into an array of Strings, what would you do?

public static void main(String args[]){

        System.out.print("new array is: ");
        for(int i = 0; i<oldArray.length; i++){
            newArray[i] = oldArray[i][0];
             System.out.print(newArray[i]);
        }

like this?
but it shows this error:
Exception in thread "main" java.lang.NullPointerException
new array is: at test.testing.main(testing.java:33)
Java Result: 1
:-/

Yes, that's right. So you've got a problem with the declaration of newArray. Where is it declared?

ah! got it! thanks :D
but strangely it loops 2 times :?:

This article has been dead for over six months. Start a new discussion instead.