Reputation: 1180
I am reading a file with the city and its population.
the file looks like this:
New York city
NY 8,175,133
Los Angeles city
CA 3,792,621
............
The format of the original file is different but I can't modify my code to read it properly. The original file looks like this:
New York city NY 8,175,133
Los Angeles city CA 3,792,621
...........
I posted the code (below) that works for the first version, but how can I make it to work for the original format? I am trying to make the city my key and the state & population as the value. I know it's something simple but I can't figure out what it is.
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner reader = new Scanner(file);
HashMap<String, String> data = new HashMap<String, String>();
while (reader.hasNext())
{
String city = reader.nextLine();
String state_pop = reader.nextLine();
data.put(city, state_pop);
}
Iterator<String> keySetIterator = data.keySet().iterator();
while (keySetIterator.hasNext())
{
String key = keySetIterator.next();
System.out.println(key + "" + data.get(key));
}
}
Thank you.
Upvotes: 0
Views: 1032
Reputation: 20211
Perhaps something like:
while (reader.hasNext())
{
String line = reader.nextLine();
int splitIndex = line.lastIndexOf(" city ");
data.put(line.substring(0, splitIndex + 5), line.substring(splitIndex + 6));
}
Upvotes: 1
Reputation: 4464
Just replace your code where you call readLine
with something like this:
String line = scannner.readLine();
int space = line.lastIndexOf(' ', line.lastIndexOf(' ') - 1);
String city = line.substring(0,space);
String statepop = line.substring(space+1);
then put your city
and statepop
into your map.
Basically, this code finds the second last space and splits your String
there.
Upvotes: 2