[英]Reading file into HashMap
我正在讀取有關城市及其人口的文件。
該文件如下所示:
紐約市
紐約8,175,133
洛杉磯市
CA 3,792,621
............
原始文件的格式不同,但是我無法修改代碼以正確讀取它。 原始文件如下所示:
紐約市NY 8,175,133
洛杉磯市CA 3,792,621
...........
我在下面發布了適用於第一個版本的代碼,但是如何使它適用於原始格式? 我正在努力使這座城市成為我的鑰匙,並將州和人口作為價值。 我知道這很簡單,但我不知道是什么。
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));
}
}
謝謝。
只需將您調用readLine
代碼替換為如下代碼:
String line = scannner.readLine();
int space = line.lastIndexOf(' ', line.lastIndexOf(' ') - 1);
String city = line.substring(0,space);
String statepop = line.substring(space+1);
然后將您的city
和statepop
加入地圖。
基本上,此代碼查找倒數第二個空格,然后在此處拆分String
。
也許像這樣:
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.