Home > Software design >  How would I be able to scan a CSV file in order to store the values into a HashMap?
How would I be able to scan a CSV file in order to store the values into a HashMap?

Time:07-31

I am trying to scan a CSV file of locations (Ordered: "Location#, Latitude, Longitude") in order to be able to store the values into a HashMap<String, LatLon>; where LatLon is a class I created so that I can store the 2 doubles of Latitude and Longitude for its key (The Location). My issue is that I can't seem to find a way to be able to store these values. I am using a scanner and I tried the following :

String path = "fileName.csv";
Scanner s = new Scanner(new File(path));

HashMap<String, LatLon> maps = new HashMap<>();


s.useDelimiter(",");

double lat = 0;
double lon = 0;

LatLon latsLons = new LatLon(lat,lon);

while(s.hasNextLine()){
   
   lat = s.nextDouble();
   lon = s.nextDouble();

    maps.put(s.next(),latsLons);
}
        
s.close();

I play around with it and try different stuff but to no avail. This case in particular produces an InputMismatchException. Any input on how to deal with this issue would be appreciated.

CodePudding user response:

CSV file of locations (Ordered: "Location#, Latitude, Longitude")

You've a Location entry in each line of the file. When you're trying to call s.nextDouble(), the InputMismatch occurs as the Location is not double. You can take the location first calling s.next() and then call those two s.nextDouble()s.

Also, you can do String line = s.nextLine() and String[] data = line.split(",") approach. In this way you'll get your location in data[0], lat in data[1] and lon in data[2] as string.

CodePudding user response:

Define a record to hold your data.

record Place ( String location, double latitude , double longitude ) {}

Use Files.lines to read the rows of data from your file as a stream of String objects.

  • Related