java - Read a csv file and separate lines into key and value to put in a hash table -
so little info program, implemented hash table separate chaining handle collisions.
class tableinput{ object key; object value; tableinput(object key, object value){ this.key = key; this.value = value; } } abstract class hashtable { protected tableinput[] tableinput; protected int size; hashtable (int size) { this.size = size; tableinput = new tableinput[size]; (int = 0; <= size - 1; i++){ tableinput[i] = null; } } abstract int hash(object key); public abstract void insert(object key, object value); public abstract object retrieve(object key); } class chainedtableinput extends tableinput { chainedtableinput(object key, object value){ super(key, value); this.next = null; } chainedtableinput next; } class chainedhashtable extends hashtable { chainedhashtable(int size) { super(size); // todo auto-generated constructor stub } public int hash(object key){ return key.hashcode() % size; } public object retrieve(object key){ chainedtableinput p; p = (chainedtableinput) tableinput[hash(key)]; while(p != null && !p.key.equals(key)){ p = p.next; } if (p != null){ return p.value; } else { return null; } } public void insert(object key, object value){ chainedtableinput entry = new chainedtableinput(key, value); int k = hash(key); chainedtableinput p = (chainedtableinput) tableinput[k]; if (p == null){ tableinput[k] = entry; return; } while(!p.key.equals(key) && p.next != null){ p = p.next; } if (!p.key.equals(key)){ p.next = entry; } } public double distance(object key1, object key2){ final int r = 6373; double lat1 = double.parsedouble(object); } }
now have csv file contains city names, latitude , longitude. need read csv file command line argument , input city names keys in hash table , latitude , longitude value. question how can read csv file , separate data key , value objects put in hash table?
something -
string csvfilepath = args[0]; bufferedreader br = null; string line = ""; string cvssplitby = ","; hashtable chainedhashtable = new chainedhashtable(100); try { br = new bufferedreader(new filereader(csvfilepath)); while ((line = br.readline()) != null) { // use comma separator string[] cityrow = line.split(cvssplitby); string cityname = cityrow[0]; double latitude = double.parsedouble(cityrow[1]); double longitude = double.parsedouble(cityrow[2]); coordinate coordinate = new cordinate(latitude, longitude); chainedhashtable.insert(cityname, coordinate); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (numberformateexception e) { e.printstacktrace(); } { if (br != null) { try { br.close(); } catch (ioexception e) { e.printstacktrace(); } } } class coordinate { double latitude; double longitude; coordinate (double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } // other setters , getters }
Comments
Post a Comment