(1)1~1000的所有奇数存储到list中
(2)把list中所有的素数删除
奇数的存储很容易;
由于ArrayList的remove()方法执行后,list的长度会发生变化,不利于循环遍历;
使用迭代器Iterator使得操作简单
import java.util.ArrayList;
import java.util.Iterator;import java.util.List;
public class Test1 {
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
for(int i=1;i<1000;i=i+2){
a.add(new Integer(i));
}
Iterator it = a.iterator();
while(it.hasNext()){
int key = ((Integer)it.next()).intValue();
if(key == 3)
it.remove();
for(int j = 2;j<=key/2;j++){
if(key%j==0)
break;
if(j == key/2){
it.remove();
System.out.print(key+" ");
}
}
}
}
}
筛选奇数与删除素数
本文介绍了一个Java程序,该程序首先将1至1000之间的所有奇数存储到一个列表中,然后通过迭代器遍历并删除其中的所有素数。文中详细展示了如何使用迭代器来避免直接修改列表导致的遍历问题。
961

被折叠的 条评论
为什么被折叠?



