gpt4 book ai didi

java - Person 不能转换为 HashMap

转载 作者:行者123 更新时间:2023-11-29 08:40:47 26 4
gpt4 key购买 nike

我想我理解错误消息的意思,我有一个人,并试图将它转换为 HashMap ,但这不是代码所说的?我不明白我做错了什么。当我阅读代码时,我没有发现任何问题..我已经坚持了一段时间了。如果我错过了一些基本的东西,我很乐意听到它,因为我只是没有收到这个错误消息

//Variable HashMap
public static HashMap<String, Person> personer = new HashMap<String, Person>();

//Method newPerson
public HashMap<String, Person> newPerson(String name) {
Person person = new Person(name);
return personer.put(name, person);
}

//Method to read file
public void readFile(String filnavn) throws Exception {
String line;
String current;

File file = new File(filnavn);
Scanner in = new Scanner(new File(filnavn));
while (in.hasNextLine()) {
line = in.nextLine();
personer.put(newPerson(line));
}
}

返回时 personer.put(name, person);我收到错误消息说不兼容的类型:Person cannot be converted to HashMap< String, Person >;

我在 personer.put(newPerson(line)) 也遇到了错误;说没有找到合适的方法,但我认为这两个错误是相关的?

最佳答案

您的代码中存在一些逻辑问题,personer.put(name, person)返回 Person不是HashMap<String, Person>
在你的readFile你打开了一个文件两次

    File file = new File(filnavn);
Scanner in = new Scanner(new File(filnavn)); // new File(filnavn), you didn't use the file !

我想你想阅读每行包含人名的文件。
你可以这样做

//Method to read file
public void readFile(String filnavn) throws Exception {
String line;
String current; // you didn't use this variable !

File file = new File(filnavn);
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
line = in.nextLine();
personer.put(line,new Person(line)); // you don't need the newPerson(String name) method
}
}

关于java - Person 不能转换为 HashMap<String, Person>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420655/

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