0

I've got a string with many lines and in each line contains a number of elements. I'm only after a third element of each line. Is there anything from with this chunk of code?

String[] separate = getArray().split("\n");
for (int i = 0; i < separate.length; i++)
{
    String[] inner = separate[i].split("/");
    for (int y = 0; y < inner.length; y++)
    {
        _listArray.add(String.valueOf(inner[2]));                   
    }
}

it's not doing what it's supposed to, or maybe I'm just too tired.

3
  • 6
    You have to describe the problem better than "it's not doing what it's supposed to". How is it not working? Commented Apr 16, 2013 at 18:38
  • Are you sure that getArray() returns the original string in the correct format with all the lines separated by \n ? Commented Apr 16, 2013 at 18:41
  • 1
    Why are you calling String.valueOf( )? inner[2] is already a String Commented Apr 16, 2013 at 18:41

2 Answers 2

3

The inner loop is not needed.

String[] lines = getArray().split("\n");
for (String line : lines) {
  String[] tokens = line.split("/");
  _listArray.add(tokens[2]);
}

You may want a safety to make sure that tokens.length >= 2

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

Comments

2

Isn't it suppose to be:

String[] separate = getArray().split("\n");
for (int i = 0; i < separate.length; i++)
{
String[] inner = separate[i].split("/");
if(inner.length<3)
     throw new RuntimeException("Wrong data");//or ignore line as desire
else _listArray.add(String.valueOf(inner[2]));                   
}

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.