Reputation: 41
I'm writing a constructor for class LatLong
that should take a string representation such as "3430E 5256N"
,and convert that to two double numbers, latitude and longitude.
How should I do that?
I wrote this so far but don't know how to remove the E and N when splitting:
public LatLong(String latlong) {
String[] parts = latlong.split(" ");
String latitude = parts[0];
String longitude = parts[1];
}
Also, if a user entered 34.5, it it will take 34 and multiply 0.5*60
to get the minutes which is 30
, which would look like 3430
, and depending on the number, it should determine what cardinality it is - North, South, East, or West.
Upvotes: 2
Views: 1111
Reputation: 725
String coordinates = "3430E 5256N";
String[] split = coordinates.split(" ");
String latitude = split[0];
String longitude = split[1];
int indexOfPoint = latitude.indexOf(".");
if (indexOfPoint != -1) {
//we don't have point in string representations, so just remove the letter
latitude = latitude.replace("E", "");
latitude = latitude.replace("W", "");
} else {
//the string representation contains a point
String valueAfterPoint = latitude.substring(indexOfPoint);
valueAfterPoint = valueAfterPoint.replace("E", "");
valueAfterPoint = valueAfterPoint.replace("W", "");
double minutes = Double.parseDouble(valueAfterPoint);
minutes*=60;
latitude+=minutes;
}
//the samething with longitude, just remove letters N and S in replace statements.
Upvotes: 0
Reputation: 436
You can do this to remove any last letter of a string, use:
String latitude = parts[0].substring(0,parts[0].length()-1);
String longitude = parts[1].substring(0,parts[1].length()-1);
Upvotes: 0
Reputation: 564
You can simply retrieve the double values from the input string using Scanner
.
Double lat, long;
Scanner scanner = new Scanner(latlong);
scanner.useDelimiter("[^\\d,]");
while (scanner.hasNextDouble() || scanner.hasNext()) {
if (scanner.hasNextDouble()) {
if (lat == null) {
lat = scanner.nextDouble(); // First setting the latitude
} else {
long = scanner.nextDouble(); // Then longitude and stopping
break;
}
} else {
scanner.next();
}
}
scanner.close(); // Edit: forgot the close in original answer
Any other conversions (as you mentioned 34.5 as input) can be done easily afterwards once you have the doubles themselves.
Note that the E and N letters are part of the latitude and longitude definitions. Regardless your question, I believe that you should eventually save them also.
Upvotes: 0