开发者

Java array list loop and return of String[] of select pairs of elements

I need to write a method that loops through ArrayList<String> pathClientStatic and then copies certain elements to a String[].

pathClientStatic is an ArrayList containing a string of timestamp x y

Each is seperated by a space " ", and there will always be a tuple though the number of tuples varies with how long the path is. So there may be timestamp x y timestamp x y timestamp x y or simply timestamp x y.

If there is more than a pair of tuples in the ArrayList, ie timestamp x y timestamp x y what I want is to copy x y x y of the final pair of tuples in the array, so the very last x y and the penultimate x y, out and into the String[]. At the moment I have the code below;

    public static String[] returnLastFour()
    {
    String data = "";
    int pathSize = pathClientStatic.size();
    if (pathSize > 6)
    {
        data += pathClientStatic.get(pathClientStatic.size()-5) + " ";
        data += pathClientStatic.get(pathClientStatic.size()-4) + " ";
        data += pathClientStatic.get(pathClientStatic.size()-2) + " ";
        data += pathClientStatic.get(pathClientStatic.size()-1);
    }
    else 
    {
        data += "nothing";
    }
    data.trim();
    String[] lastFour = data.split(" ");
    return lastFour;
    }

Though for some reason it doesn't always pull out the last two x y pairs. For example when the ArrayList contains;

15:29:20.841 137.0 137.0 15:29:20.841 137.0 137.0 15:29:20.841 28.0 45.0

What I want the String[] to end with is;

137.0 137.0 28.0 45.0

But instead I get;

137.0 137.0 137.0 45.0

I imagine it's just an obvious mistake but I have been staring/playing with this code for so long I just see a haze now.

Help appreciated开发者_高级运维.


The code looks correct to me. Are you absolutely certain of your inputs?

PS -- It's best to use StringBuilder instead of data += ...

Edit

Now I'm positive: you'll get 137.0 137.0 28.0 45.0 if you run this program on the input you listed. Check the code that populates your original array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜