I'm trying to read a comma delimited CSV file that displays the city, country, latitude and longitude in each row. The goal of my project is to print a statement that shows all cities in the southern hemisphere, which means reading the latitude of each row and converting those strings into integers. The problem is I keep getting a "NumberFormatException" while trying to parse the string, and I'm assuming its because some of these string numbers are negative values.
The latitude values the reader is converting are : 39, -57, -25, 35 The error throws a NumberFormatException at the input string latitude when all are proper integer, so I can only assume its because of the dash in the integers that stops it from parsing into a integer.
My code reads each line and splits it into tokens so I can evaluate each columns separately, and see if the parsed integer value of the latitudes are less than zero. This shows that the city with that latitude resides in the southern hemisphere and I can then add it to my ArrayList of cities that are in the Southern Hemisphere for me to print later.
String path = args[0];
String delimiter = ",";
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
ArrayList<String> cities = new ArrayList<String>();
reader.skip(1);
while (reader.ready()) {
String line = reader.readLine();
String[] tokens = line.split(delimiter);
if (Integer.parseInt(tokens[2]) < 0) {
cities.add(tokens[0]);
}
}
Any suggestions on how to fix this?
Remove whitespace before parsing
The error is not a result of the negative symbol (HYPHEN-MINUS character), but because of the whitespace (a SPACE character, in your case).
If your input data is truly as you pasted in the question, your latitude token is not
"-25", it is:… with a SPACE in front. Add a trim() before you attempt to parse, and you'll be all set.
Tip: To discover such non-obvious characters while debugging, you can get the code point and name of each character.
See this code run at Ideone.com.