简体   繁体   中英

List Array and String Array / multi-line string inside of nested loop in Android Java

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.

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

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]));                   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM