【发布时间】:2015-10-21 03:37:55
【问题描述】:
我正在尝试通过使用迭代器对其进行迭代来从 LinkedList 中删除素数。我有以下代码
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);
}
}
它会删除某些素数,但不会删除其他素数。谢谢你的帮助。我正在尝试在 main 方法中完成所有这些操作,而无需类。
【问题讨论】:
-
您正在设置
ListIterator并且几乎不使用它。我建议您重新设计循环以使用迭代器,特别是它的remove()方法。
标签: java linked-list iterator primes