2017-03-08 1 views
0

저는 작은 학생 명단을 관리하는 프로젝트를 진행하고 있습니다. 필수 기능 중 하나는 학생 ID를 사용하여 학생의 기록을 삭제하고 학생 ID가 없으면 삭제 기능으로 오류를 줄 수있는 기능입니다.Java : 배열 목록에서 제거하는 동안 런타임 오류가 발생했습니다.

이 제거 확인에 필요한 테스트는 동일한 학생 ID를 두 번 제거하고 두 번째로 제거 메소드가 호출 될 때 오류 메시지가 인쇄되는지 확인하는 것입니다.

첫 번째 제거 메소드 호출이 작동 중이며 호출 된 학생 ID에 대한 요소가 성공적으로 삭제됩니다. 그러나 두 번째 제거에서는 동시 변경 예외 오류가 발생합니다.

다음 코드는 Student 배열 목록을 만들고 remove 메서드를 두 번 호출합니다.

static ArrayList<Student> myRoster = new ArrayList<>(); 

public static void main(String[] args) 
{ 
    // add students to the roster 
    add("1", "John", "Smith", "[email protected]", "20", 
    88, 79, 59); 
    add("2", "Suzan", "Erickson", "[email protected]", "19", 
    91, 72, 85); 
    add("3", "Jack", "Napoli", "The_lawyer99yahoo.com", "19", 
    85, 84, 87); 
    add("4", "Erin", "Black", "[email protected]", "22", 
    91, 98, 82); 

    //loop through the ArrayList and for each element: 
    remove("3"); 
    remove("3"); 

다음은 제거 방법입니다. 이것이 어떻게 작동해야하는지에 대한 현재의 생각은 다음과 같습니다.

* 학생 ID가 있는지 먼저 확인하려면 if/else를 삽입하여 if/else 루프에 포함 된 학생을 삭제하십시오.

* 포함 목록에 학생 ID가 포함되어 있는지 보려면 contains를 사용합니다. 그렇다면 if/else가 제거됩니다. 그렇지 않으면 실패한 인쇄물이 반환되고 반환됩니다. 여기

public static void remove(String studentID) 
    //remove student from roster by student ID 
    //print error message if student is not found 
    { 
     for(Student b: myRoster) 
     { 
      String record = b.getStudentID(); 
      Boolean a = studentID.contains(studentID); 
      if (a) 
      { 
       Boolean c = record.matches(studentID); 
       if (c) 
       { 
        myRoster.remove(b); 
        System.out.println("Student ID " + studentID + " was removed."); 
       } 
      else 
       { 
        ; 
       } 
      } 
      else 
      { 
       System.out.println("Student ID does not exist."); 
      } 

나는 오류 받고 있어요된다

java.util.ConcurrentModificationException 
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) 
at java.util.ArrayList$Itr.next(ArrayList.java:851) 
at Roster.remove(Roster.java:48) 
at Roster.main(Roster.java:28) 
java.util.ConcurrentModificationException 
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) 
at java.util.ArrayList$Itr.next(ArrayList.java:851) 
at Roster.remove(Roster.java:48) 
at Roster.main(Roster.java:28) 

어떤 아이디어?

+2

당신은 foreach 루프에서 제거 할 수 없습니다. 일반 for 루프를 사용하십시오. –

+0

가능한 [Java 프로그래밍 오류 : java.util.ConcurrentModificationException] 복제본 (http://stackoverflow.com/questions/8553713/java-programming-error-java-util-concurrentmodificationexception) –

답변

1

목록의 내용을 반복자를 사용하여 반복하는 동안 안전하게 수정할 수 없습니다. 이 작업을 수행하려면 ListIterator을 사용하십시오.

ListIterator<Student> it = myRoster.listIterator(); 
while (it.hasNext()) { 
    Student b = it.next(); 
    if (b.getStudentId() == studentId) { 
     it.remove(); // Removes b from myRoster 
    } 
    ... 
} 

학생 수가 많으면 잘 확장되지 않습니다. Map<String, Student> 키를 학생 ID로 사용하여 더 잘 수행 할 수 있습니다.

0

학생 ID가 빈칸으로 남겨진 루프의 첫 번째 부분에 존재하지 않는다고 말하고 싶지 않으십니까?

if (a) 
{ 
    Boolean c = record.matches(studentID); 
    if (c) 
    { 
     myRoster.remove(b); 
     System.out.println("Student ID " + studentID + " was removed."); 
    } 
    else 
    { 
     System.out.println("Student ID does not exist."); 
    } 
} 
0

이 시도 :

for(Iterator<String> it = myRoster.iterator(); it.hasNext();) { 
    String b = it.next(); 
    ... 
    if (...) { 
     it.remove(); 
     ... 
    } 
    ... 
} 
관련 문제