1

I have a csv file that I will read in the code. But when I run the code it is showing me this error:

    Exception in thread "main" java.lang.NumberFormatException: For input string: "lon"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.base/java.lang.Double.parseDouble(Double.java:543)
    at practise.main(practise.java:63)

please help me with this.

Here is my code:

    s1 = new Scanner(new FileReader(filename2+".csv"));
    while(s1.hasNext()){
        z = s1.nextLine();

        String[] results = z.split(",");
        double[] lon_lat = new double [2];
        lon_lat[0] = Double.parseDouble(results[1]);//longtitude
        lon_lat[1] = Double.parseDouble(results[2]);//latitude
        airportLonLat.put(Integer.parseInt(results[0]), lon_lat);
    }

And here is my csv data:

Id     lon      lat
1     -5.9300   54.5906
2     -5.9385   54.6013
3     -5.9191   54.5928
4     -5.9171   54.5992
5     -5.9273   54.5873
.......................
30    -5.9582   54.5834
2
  • It's a good practice to name your variables based on what they represent, so that the code is more readable and understandable even if you come back to it after two weeks. s1 and z can be whatever. Commented Mar 9, 2021 at 17:33
  • @Dropout Thank you. I will do that. Commented Mar 9, 2021 at 17:35

1 Answer 1

2

The program starts reading from the first line, which contains the headers. You are getting the "NumberFormatException" because it is attempting to convert the header (which is a string) to a double.

To resolve this, you can either remove the headers from the data or add a condition to skip the first row.

Hopefully, that resolves the issue.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I get it now. That's the reason. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.