import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; public class Javatest83 { /** * 集合-Collection(ArrayList、LinkedList等) * 练习2:提示用户输入整数,存放到ArrayList集合中, * 输入0代表结束。分别使用for、foreach、iterator循环集合,并删除所有是3的倍数的元素 */ public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); System.out.println("请输入整数,输入0代表结束:"); Scanner sc = new Scanner(System.in); int i = sc.nextInt(); while(i != 0){ list.add(i); System.out.println("请输入整数,输入0代表结束:"); i = sc.nextInt(); } //for遍历 for (int j = 0; j < list.size();) { if(list.get(j) % 3 == 0) list.remove(j); else j++; } System.out.println(Arrays.toString(list.toArray())); //foreach遍历 for (Integer m:list) { System.out.println(m); } //Iterator遍历 Iterator it = list.iterator(); while (it.hasNext()){ int tep = (int)it.next(); if(tep % 3 == 0){ it.remove(); } else System.out.println(tep); } } }