我打算用静态方法创建一个类,该类需要执行以下操作:
我确实相信我已经差不多完成了这项任务,但是,我的最新问题是StackOverflowError的一个极端情况,我似乎无法找到解决方案。以下是相关信息:
首先,这是我要编写一个符合以下条件的类,它是该类提供的,不可编辑的主类。
public static void main(String[] args) //this is line 6 for reference
{
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));
}
这是我编写的课程,几乎可以按预期工作了:
public Employee(String b) { //this is line 6 for reference
Map<String, Employee> m=load(); //line 7
if (m.containsKey(b)){
String value=m.get(b).toString();
System.out.println(b+" -> "+value);
}
}
public static Map<String,Employee> load() {
File f=new File("employees.txt");
Map<String,Employee> result=new LinkedHashMap<>();
String ID = null;
String name = null;
try {
BufferedReader in = new BufferedReader(new FileReader(f)); //line 20
String line;
String[] values;
int i=0;
while(((line=in.readLine())!=null)){
if (i>0){ //this skips the first line with irrelevant informaion
line=in.readLine();
values= line.split(" ", 2);
ID=values[0];
if (values.length>1){
name= values[1].replaceAll("\\s{2,}"," ").trim();}}
i++;}
} catch (IOException e) {
e.printStackTrace();
}
Employee e= new Employee(name); //line 35
result.put(ID, e);
return result;
}
应该发生的一个例子是程序应该以这种方式工作:
输出:输入您要查找的员工的ID
输入:39-7290036
输出:39-7290036-> Elroy Bevis ebevish@hc360.com
但是相反,程序甚至在没有输入请求的初始输出之前就崩溃了。 发生的错误如下:
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.nio.ByteBuffer.limit(ByteBuffer.java:265)
at java.base/java.nio.Buffer.<init>(Buffer.java:223)
at java.base/java.nio.ByteBuffer.<init>(ByteBuffer.java:284)
at java.base/java.nio.HeapByteBuffer.<init>(HeapByteBuffer.java:63)
at java.base/java.nio.ByteBuffer.allocate(ByteBuffer.java:351)
at java.base/sun.nio.cs.StreamDecoder.<init>(StreamDecoder.java:264)
at java.base/sun.nio.cs.StreamDecoder.<init>(StreamDecoder.java:244)
at java.base/sun.nio.cs.StreamDecoder.forInputStreamReader(StreamDecoder.java:79)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:74)
at java.base/java.io.FileReader.<init>(FileReader.java:75)
at Employee.load(Employee.java:20)
at Employee.<init>(Employee.java:7) //these last two lines repeat for several upon several more lines
at Employee.load(Employee.java:35)
答案 0 :(得分:0)
由于load()
方法创建了一个新的Employee对象,并且在Employee load()
的构造函数内部被调用,依此类推,因此得到了
您的Employee构造函数应类似于
public Employee(String id, String name) {
this.id = id
this.name = name
}
并且您需要在load
的while循环内创建一个新的Employee,因此请将其添加到while循环的末尾,即i ++行之前
Employee employee = new Employee(ID, name);
result.put(ID, employee);
并在while循环后删除相应的行