user14570244
user14570244

Reputation:

Read csv file and taking input in java

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

Upvotes: 1

Views: 558

Answers (1)

Praise
Praise

Reputation: 328

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.

Upvotes: 2

Related Questions