How do I check whether a string fits this format:
<number>,<number>,<number>
e.g.
3.0, 87546,0.8273456
i.e. three comma-separated values that can be parsed as doubles. Sometimes the string will contain something else (e.g. Text,More text,42 or anything, really) and in such a case I just need to ignore it and move on to parsing the next string.
Right now I just try to parse the string as if it fits the expected format, and catch any resulting exception. What is a smarter and less expensive way of doing this? Hopefully without throwing/catching exceptions?
String[] parsedLine = line.trim().split(",");
if (parsedLine.length == 3) {
try {
xCoordinate = Double.parseDouble(parsedLine[0]);
yCoordinate = Double.parseDouble(parsedLine[1]);
groundElevation = Double.parseDouble(parsedLine[2]);
} catch (NumberFormatException nfe) {
//This line does not contain numbers exclusively.
//Assume it's a header/comment.
//Do nothing.
}
} else {
//This is not in the expected x,y,z format.
//Assume it's a header/comment.
//Do nothing.
}
What you have right now is probably the most bullet-proof (and in my view the easiest to understand) implementation possible.
I wouldn’t change it, unless I had specific evidence from the profiler that it’s an overall bottleneck (either in terms of CPU usage, or the amount of garbage created).