gpt4 book ai didi

java - 将 CSV 文件解析为 HashMap 存储空值

转载 作者:行者123 更新时间:2023-12-01 18:06:04 25 4
gpt4 key购买 nike

我正在尝试读取 csv 文件并将数据存储到 HashMap 中。我能够正确添加键,但是在添加值时,它会为每个值添加 null 。我不知道为什么。这是我的代码:

编辑代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class ExampleActivity {
public static HashMap<String, String> hm = new HashMap<String, String>();

public static void readCountry() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("countries.csv"));
String line;
HashMap<String, String> hm = new HashMap<String, String>();

while ((line = reader.readLine()) != null) {
String str[] = line.split(",");
if (str.length > 1) {
System.out.println("Data 0: " + str[0]);
System.out.println("Data 1: " + str[1]);
hm.put(str[0].trim(), str[1]);
}

}
//System.out.println(hm);
}

public static void main(String[] args) throws IOException {

readCountry();

Scanner in = new Scanner(System.in);
String l = null;

System.out.println("Please enter a three letter country:");
l = in.nextLine();
l = l.trim();
// System.out.println("Country Code: " + l + "\nCountry Name: " +
// hm.get(l) );
if (hm.containsKey(l)) {
System.out.println("Country Code: " + l + "\nCountry Name: "
+ hm.get(l));
} else {
System.out.println("Missing key for " + l);
}
}
}

这是 CSV 文件的示例

AFG,Afghanistan
AGO,Angola
AIA,Anguilla
...

这是输出的屏幕截图: enter image description here

最佳答案

注释掉 hashmap 的方法本地声明,它应该可以正常工作。修改代码如下:

public static void readCountry() throws IOException{

BufferedReader reader = new BufferedReader(new FileReader("d:/countries1.csv"));
String line;
// HashMap<String, String> hm = new HashMap<String, String>(); Remove this line

关于java - 将 CSV 文件解析为 HashMap 存储空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36349179/

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