How to parse a negative value String from a delimited CSV File

65 Views Asked by At

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?

2

There are 2 best solutions below

1
Jacob On

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:

" -25"

… with a SPACE in front. Add a trim() before you attempt to parse, and you'll be all set.

Integer.parseInt(tokens[2].trim())

Tip: To discover such non-obvious characters while debugging, you can get the code point and name of each character.

String input = " -25" ;
input
    .codePoints()
    .mapToObj( (int codePoint) -> String.valueOf( codePoint ) + " = " + Character.getName( codePoint ) )
    .forEach( System.out :: println ) ;

See this code run at Ideone.com.

32 = SPACE
45 = HYPHEN-MINUS
50 = DIGIT TWO
53 = DIGIT FIVE
2
queeg On

Although Jacob found a likely problem, instead of creating your own parser use a mature library like commons-csv.

On this user guide page you can find several examples: https://commons.apache.org/proper/commons-csv/user-guide.html