【发布时间】:2020-11-10 02:24:46
【问题描述】:
我打算创建一个类来读取包含员工信息(ID 号、姓名和电子邮件)的文本文档,并将信息转换为包含两个组件的 Map:带有 ID 号的字符串和 Employee 对象名称和电子邮件,由一个空格分隔(与文本文档中的两个空格相反)。我(几乎)通过创建一个程序来解决这个问题,该程序成功地遍历文本文档,将每一行分成三部分,除以每组两个连续的空格,然后将最后两部分加在一起。但是,由于此时最后一部分是字符串格式,我需要将其转换为 Employee 对象,然后才能将其插入
这是我要遵守的类提供的(不可编辑的)主类:
public static void main(String[] args)
{
Map<String, Employee> data = Employee.load();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter ID of employee you're looking for");
String id = keyboard.nextLine();
System.out.println(data.get(id));
}
这是我尝试创建要返回的正确 HashMap 的类:
public static Map<String,Employee> load() {
File f=new File("employees.txt");
Map<String,Employee> result=new LinkedHashMap<>();
String ID = null;
String name = null;
String email = null;
String b;
try {
BufferedReader in = new BufferedReader(new FileReader(f));
String line;
String[] values;
int i=0;
while(((line=in.readLine())!=null)){
line=in.readLine();
values= line.split(" ");
if (i>0){
//this is meant to ignore the first line, as it contains irrelevant information
ID=values[0];
name= values[1];
email=values[2];}
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
b=name+" "+email;
result.put(ID, (Employee) b); //"(Employee) b" has an error that reads:
//Inconvertible types; cannot cast 'java.lang.String' to 'Employee'
return result;
}
}
【问题讨论】: