Search code examples
javaandroidadb

Java .split weird outcome


I'm trying to split up a string, but it doesn't seem to give the correct output this is the string being passed around

1#0:250:250:

I first do this

String[] dataArray = data.split("#");

this gives me

1
0:250:250:

I then do this

for( int i = 0; i < totalPlayers; i++)
            {
                String[] pos = dataArray[i++].split(":");
                if( Integer.parseInt( pos[0] ) == ID )
                {
                    //do nothing
                }
                else
                {
                assets[i].setPosition( Integer.parseInt( pos[1] ),     Integer.parseInt( pos[2] ) );
                }
            }

I get an error saying ArrayIndexOutOfBoundsException, if i print out pos[0] i get 1, if i print out pos[1] i get ArrayIndexOutOfBoundsException, Why isn't my string being split up into

0
250
250

?

Cheers

Canvas


Solution

  • You have an error in your code that is causing it to split 1 instead of 0:250:250: . Recall that the postfix increment operator (e.g. i++) increments the variable after it is used in the expression. So the first line in the loop is really saying String[] pos = dataArray[i].split(":"); i = i + 1; .

    The simple fix would be to change i++ to ++i, which would essentially make the line run as i = i + 1; String[] pos = dataArray[i].split(":"); . However, this exact bug is why using ++ operators inside complex statements can be confusing and is often discouraged. Moreover, incrementing your loop variable outside of your for statement can lead to additional confusion.

    Since the idea you really want to express is 'loop through the array by pairs', I would recommend writing something like

    for (int i = 0; i < totalPlayers; i += 2) {
        String[] pos = dataArray[i + 1].split(":");
        // (the same as above)
    }