删除每个第n名员工都没有工作

时间:2017-10-28 13:10:49

标签: java

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class vijftienpunt1 {

public static void downsize(LinkedList<String> employeeNames, int n) {
    for (int i = 0; i < employeeNames.size(); i++) {
        if(i%n==0) {
            employeeNames.remove(i);
        }
    }
}

public static void main(String[] args) {
    LinkedList<String> employeeNamess = new LinkedList<String>();

    employeeNamess.add("Ab");

    employeeNamess.add("Yo");
    employeeNamess.add("Ik");
    employeeNamess.add("Jij");

    System.out.println(employeeNamess);
    downsize(employeeNamess, 2);
    System.out.println(employeeNamess);
}
}

当我运行它不起作用时,它会删除其他第n个元素,我该如何解决这个问题。我尝试过更多操作,但它仍然无法正常工作

1 个答案:

答案 0 :(得分:2)

如果要从列表中删除元素,请使用Iterator。

尝试以下代码:

public static void downsize(LinkedList<String> employeeNames, int n) {
    int i=1;
    Iterator<String> iter=employeeNames.iterator();
    while(iter.hasNext()){
        iter.next();
        if(i%n==0) {
            iter.remove();
        }
        i++;
    }
}