[英]Reading file into HashMap
I am reading a file with the city and its population. 我正在读取有关城市及其人口的文件。
the file looks like this: 该文件如下所示:
New York city 纽约市
NY 8,175,133 纽约8,175,133
Los Angeles city 洛杉矶市
CA 3,792,621 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 纽约市NY 8,175,133
Los Angeles city CA 3,792,621 洛杉矶市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. 谢谢。
Just replace your code where you call readLine
with something like this: 只需将您调用readLine
代码替换为如下代码:
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. 然后将您的city
和statepop
加入地图。
Basically, this code finds the second last space and splits your String
there. 基本上,此代码查找倒数第二个空格,然后在此处拆分String
。
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.