0

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 by Nick Evan: Fixed formatting

2
Contributors
8
Replies
10
Views
6 Years
Discussion Span
Last Post by gingerfish
0

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"};

0

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

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

0

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.

0

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 by gingerfish: n/a

0

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?

0

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
:-/

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.