Splitting Java strings and extracting numbers
Archive - Originally posted on "The Horse's Mouth" - 2015-01-13 17:44:28 - Graham EllisIn Java you can use packages in the utility class to handle strings, or you can use methodsin java.lang.String which has been enhanced from version to version and now includes methods such as String.split().
Examples from today's course - taking a line of data (which could have been read from a file) and splitting it into elements which are then used to perform a calculation. [here].
That's a useful piece of code - but we've mixed up the logic of extracting the data and doing the calculation with the main program - not a good idea for the future extensibiity. So I refactored the example above - passing the string into a factory within a class to extract the data from it, and return me an object. I then ran a couple of methods on the object to do calculations that had been in the main code. Neat. Source [here].within a class to extract the data from it, and return me an object. I then ran a couple of methods on the object to do calculations that had been in the main code. Neat. Source [here].
Output ... in BOTH cases:
trainee@kingston:~/2015$ java Station
Swanseahas grown to a factor 1.5598733
trainee@kingston:~/2015$
So we're seeing a growth in traffic at Swansea station from 2005 to 2013 of 55.9%