mhollander38
mhollander38

Reputation: 775

Java loop to collect the second and third elements every three in an array

I have a file with data in the form timestamp, coordinate, coordinate, seperated by spaces, as here;

14:25:01.215 370.0 333.0

I need to loop through and add the coordinates only to an array. The data from the file is read in and put into as String[] called info, from split(" "). I have two problems, I think the end of the file has a extra " " which I need to lose appropriately and I also want confirmation/suggestions of my loop, at the moment I am getting sporadic out of bounds exceptions. My loop is as follows;

String[] info;
info = dataHolder.split(" ");
ArrayList<String> coOrds1 = new ArrayList<String>();
for (int counter = 0; counter < info.length; counter = counter+3)
{
    coOrds1.add(info[counter+1]);
    coOrds1.add(info[counter+2]);
}

Help and suggestions appreciated.

The text file is here but the class receives in a UDP packet from another class so I am unsure if this potentially adds " " at the end or not.

Upvotes: 2

Views: 4070

Answers (3)

pnt
pnt

Reputation: 1916

There is no need for external libraries.

You could just call dataHolder.trim(); which will remove any whitespace from the beginning and end your string. Then using dataHolder.split("\s"); //splits on "whitespace", you will receive an array consisting only of your data and with the appropriate size.

This will save you all the checks at each iteration whether counter+2 is still within the scope of the array. While still a valid solution, this could introduce further problems in the future due to its inherent nature of being "check-to-validate" - you simply might forget to process one of the cases - while trimming the string beforehand makes it structurally, constructed valid and there is no need to process special cases.

Upvotes: 1

finnw
finnw

Reputation: 48619

There are various classes/methods in Google's Guava library that could help with this task, in particular Splitter.omitEmptyStrings() which will discard any trailing space at the end of the file:

String input = Files.toString(file, Charsets.US_ASCII);
Iterable<String> fields =
    Splitter.on(" ")
            .omitEmptyStrings()
            .split(input);
List<Coord> coords = Lists.newArrayList();
for (List<String> group: Iterables.partition(fields, 3)) {
    String t = group.get(0);
    double x = Double.parseDouble(group.get(1));
    double y = Double.parseDouble(group.get(2));
    coords.add(new Coord(t, x, y));
}

Upvotes: 3

Jackson Pope
Jackson Pope

Reputation: 14640

The problem will occur if you have an extra space at the end, because you are testing for counter < info.length and using counter + 1 and counter + 2. Try changing the loop conditions to:

for (int counter = 0; counter + 2 < info.length; counter = counter+3)

Upvotes: 1

Related Questions