我想模拟一个简单的电话应用程序,它可以管理联系人和处理消息。我已经为我的manageContacts函数创建了一个函数,我称之为delteContact。
然而,当我尝试删除我的联系人时,我得到了这个错误,我检查了我的代码,我不明白为什么它会抛出这个错误?
private static void deleteContact() {
System.out.println("Bitte den Namen eingeben:");
String name = scanner.next();
if(name.equals("")){
System.out.println("Bitte den Namen eingeben:");
deleteContact();
}else{
boolean doesExist = false;
for(Contact c : contacts){
if(c.getName().equals(name)){
doesExist = true;
contacts.remove(c);
}
}
if(!doesExist){
System.out.println("Dieser Kontakt existiert nicht.");
}
}
showInitialOptions();
}有没有人能帮帮我,我哪里搞错了?
发布于 2021-01-16 19:29:06
for(Contact c : contacts){
if(c.getName().equals(name)){
doesExist = true;
contacts.remove(c);您正在修改增强的for循环中的集合-通常这是不允许的,因为它是由拒绝此行为的迭代器隐式控制的。迭代器正在抛出异常。
您可以通过显式声明迭代器并要求迭代器为您删除元素来解决此问题:
Iterator<Contact> i = contacts.iterator();
while(i.hasNext()){
Contact c = i.next(); //you must call next() before remove()
if(c.getName().equals(name)){
doesExist = true;
i.remove(); //call remove on the iterator, not the collection
}https://stackoverflow.com/questions/65748959
复制相似问题