Я пытаюсь удалить простые числа из LinkedList, итерации по нему с помощью Iterator. У меня есть следующий кодКак удалить простые числа из связанного списка
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Random;
public class LinkedListProcesing{
public static void main(String[] args){
int listSize = 0;
LinkedList<Integer> list = new LinkedList<Integer>();
Random randNumGen = new Random();
while(listSize<20){
int nextRand = randNumGen.nextInt(101); //while there are less than 20 random ints process a new one
list.add(nextRand); //add the new random number to the linked list
//System.out.println(nextRand);
listSize+=1; //iterate over the list size
}
System.out.println("The list contains these 20 random integers: " + list);
ListIterator iterator = list.listIterator();
int next = (Integer) iterator.next();
for (int i=2; i<list.size(); i++){
if (i>=1){
list.remove(i);
}
if (next%i!=0){
list.remove(i);
}
}
System.out.println("This is the list excluding primes: " + list);
}
}
Он удаляет некоторые простые числа, но не другие. Спасибо за любую помощь. Я пытаюсь сделать все это в основном методе, а также без необходимости в классах.
Вы настраиваете 'ListIterator' и почти не используете его. Я предлагаю вам переработать ваш цикл, чтобы использовать итератор, в частности метод 'remove()'. – rossum