2015-01-20 2 views
0

내 문제는, 내가이 코드를 출력 할 때, 내가 원하는 것을 출력하지 않고 "all"을 제거하는 것입니다. 첫 번째 print 서술문과 똑같은 것을 출력합니다.내 프로그램이 "모두"를 삭제하지 않는 이유는 무엇입니까?

// RemoveAll 
// Spec: To remove the "all" 
// ArrayList remove() exercise 

import java.util.ArrayList; 

public class RemoveAll 
{ 
public static void main(String args[]) 
{ 
    ArrayList<String> ray; 
    ray = new ArrayList<String>(); 
    int spot = ray.size() - 1; 

    ray.add("all"); 
    ray.add("all"); 
    ray.add("fun"); 
    ray.add("dog"); 
    ray.add("bat"); 
    ray.add("cat"); 
    ray.add("all"); 
    ray.add("dog"); 
    ray.add("all"); 
    ray.add("all"); 
    System.out.println(ray); 
    System.out.println(ray.size()); 

    // add in a loop to remove all occurrences of all 
    while (spot >= 0) 
    { 
     if (ray.get(spot).equalsIgnoreCase("all")) 
     { 
      ray.remove(spot); 
     } 

     spot = spot - 1; 
    } 

    System.out.println("\n" + ray); 
    System.out.println(ray.size()); 
} 
} 

어떤 아이디어 :

여기 내 코드입니까? 당신은 목록 작성 일단이 후 넣어 목록

을 채우기 전에 size()을 결정하는

답변

4

(즉, 모든 add() 후)

int spot = ray.size() - 1; 
+0

"spot"값을 배열 크기로 설정 한 다음 추가하고 다시 설정하지 않고 spot을 사용합니다. 또한, 배열을 반복하면서 remove()를 사용하여 배열을 변형하면 더욱 악화됩니다. –

+0

정말 고마워요! 오류가 수정되었습니다! – Samkough

1

목록에서 항목을 제거하는 또 다른 방법은 Iterator 사용하는 것입니다 :

for(Iterator<String> i = ray.iterator(); i.hasNext();) { 
    if(i.next().equalsIgnoreCase("all")) { 
     i.remove(); 
    } 
} 

그런 식으로 당신은 제거와 관련하여 당신이 어디에 있는지 추적 할 필요가 없습니다. 에드.

1

두 가지 문제가 있습니다. 배열에 값이 있기 전에 배열의 크기를 설정하고 있으므로 배열에 돌연변이를하는 동안 배열을 변경 (수정)하고있는 경우 while (spot >= 0)

모든 종류의 오류가 발생합니다. 원하는 방식으로 반복자를 사용하는 것입니다.
Iterator iter = ray.iterator(); 
while(iter.hasNext()){ 
String cur = iter.next(); 
//logic to determin if you need to remove 
iter.remove(); 

} 
관련 문제