1

Hi I have the array below, I need to copy the contents into another single dimensional array but only the first row e.g. 0 and 1

String data[][] = new String[][]
   {
      {"0", "1", "2", "3", "4"},
      {"1", "1", "2", "3", "4"}
   }

The above code is an example of how I have set my array, I just need the first row but for every colum

I have tried:

for (int r = 0; r < data.length; r++)
   {
    codes = new String[]  {data[r][0]};
   }

But that doesnt work, any ideas? Thanks

3 Answers 3

1

Try this:

String[] codes = new String[data.length];
for (int r = 0; r < data.length; r++) {
    codes[r] = data[r][0];
}

That should work

Sign up to request clarification or add additional context in comments.

Comments

0

Or try:

String[] codes = new String[data.length];
int i=0;
for(String[] strings : data)
{
    codes[i++]=strings[0];
}

Although honestly, since foreach code creates a counter, you may be better off using the type of loop that goatlinks showed.

Comments

0

The data contained in data[r][0] is a String. Not a String[] (Array of Strings).
What you want to do: create an array that has the same size as you have columns. String[] codes = new String[data.lenght] and then assign the [r][0] element of data to the r-th element of your newly created array: codes[r] = data[r][0]

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.