我有一个具有私有变量的类,例如employeeName和employeeNumber,以及设置和获取employeeName和employeeNumber的方法。该类称为“EmployeesInformation”。在这个类中,我有两个构造函数。获取员工信息(如EmployeesInformation(String name, String phoneNumber){...}
和另一个获取相同信息但又获得两个额外信息的信息,如字符串datefired和String reasonForLeave)。
现在在另一个名为“MenuOptionMethods”的类中,我有addEmployee方法和fireEmployee方法以及另一种显示员工信息的方法。 我在这个名为employee和formerEmployee的类中创建了两个arrayList。
每当用户添加一名员工时,我将该员工对象放在名为employee的arrayList中。当用户触发或删除我想要获取该员工所有信息的员工时,将其从arrayList员工中删除并将其添加到arrayList formerEmployee。那是我遇到问题的地方。有人可以看看我的代码并告诉我它有什么问题吗?
public class menuOptionMethods {
Scanner sc = new Scanner(System.in);
private ArrayList<EmployeesInformation> employee;
private ArrayList<EmployeesInformation> formerEmployee;
public menuOptionMethods() {
employee = new ArrayList<EmployeesInformation>();
formerEmployee = new ArrayList<EmployeesInformation>();
}
public void addEmployee(String eName) {
String n = eName;
System.out.println(" Enter date hired: ");
String h = sc.next();
System.out.println(" Enter employee's duty: ");
String d = sc.next();
System.out.println(" Enter employee's phone number: ");
String pN = sc.next();
System.out.println(" Enter employee's pay per hour: ");
double pPH = sc.nextInt();
System.out
.println(" Enter any additional information about employee: ");
String l = sc.next();
EmployeesInformation e = new EmployeesInformation(n, h, d, l, pN, pPH);
employee.add(e);
}
public void fireEmployee(String eName) {
// System.out.println("Enter employee's name: ");
// String name = eName;
System.out.println("Reason for employee's leave?: ");
String reason = sc.next();
System.out.println("Enter date: ");
String dF = sc.next();
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
n = eName;
h = employee.get(i).getDateHired();
d = employee.get(i).getEmployeDuty();
pH = employee.get(i).getPhoneNumber();
pPH = employee.get(i).getEmployePay();
l = employee.get(i).getAdditionalInformation();
employee.remove(i);
}
}
EmployeesInformation fE = new EmployeesInformation(n,h,d,l,pH,pPH,reason,dF); // ERROR HAPPENS HERE
}
}
答案 0 :(得分:0)
在使用for循环迭代它时,不能从列表中删除元素(它将抛出ConcurrentModificationException
。为此,您需要使用迭代器并调用remove()
方法,例如:
for(Iterator<Employee> iterator = employees.iterator() ; iterator.hasNext();){
Employee current = iterator.next();
if(current.getName().equals(name)){
iterator.remove();
//Add into former employees' list
break;
}
}
这将从现有列表中删除。
答案 1 :(得分:0)
在你的for循环中,你不想做任何删除,因为arraylist的大小会改变,而这只会造成让你失望的打击。假设每个员工都有一个唯一的名称,你可以做这样的事情(注意我通过将该员工对象从一个arraylist转移到另一个arraylist来简化所有这些新变量):
int index;
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
formerEmployee.add(employee[i]); //date fired and reason fired can be added later
index = i;
break;
}
}
employee.remove(i);
}