gpt4 book ai didi

java - 将文件读入HashMap

转载 作者:行者123 更新时间:2023-12-01 22:26:07 25 4
gpt4 key购买 nike

我正在阅读一份有关城市及其人口的文件。

该文件如下所示:

纽约市

纽约 8,175,133

洛杉矶市

CA 3,792,621

............

原始文件的格式不同,但我无法修改我的代码以正确读取它。原始文件如下所示:

纽约市 NY 8,175,133

洛杉矶市 CA 3,792,621

……

我发布了适用于第一个版本的代码(如下),但如何使其适用于原始格式?我试图以城市为关键,以州和人口为值(value)。我知道这很简单,但我不知道它是什么。

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);

然后将您的城市statepop放入您的 map 中。

基本上,这段代码会找到倒数第二个空格并在那里分割您的String

关于java - 将文件读入HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com