//Name: Date: import java.io.*; import java.util.*; public class IteratorLab { public static void main(String[] args) { System.out.println("Iterator Lab\n"); int[] rawNumbers = {-9, 4, 2, 5, -10, 6, -4, 24, 20, -28}; ArrayList numbers = createNumbers(rawNumbers); System.out.println("ArrayList: "+ numbers); //Implicit Iterator! System.out.println("Count negative numbers: " + countNeg(numbers)); System.out.println("Average: " + average(numbers)); System.out.println("Replace negative numbers: " + replaceNeg(numbers)); System.out.println("Delete zeros: " + deleteZero(numbers)); String[] rawMovies = {"High_Noon", "High_Noon", "Star_Wars", "Tron", "Mary_Poppins", "Dr_No", "Dr_No", "Mary_Poppins", "High_Noon", "Tron"}; ArrayList movies = createMovies(rawMovies); System.out.println("Movies: " + movies); System.out.println("Movies: " + removeDupes(movies)); } // pre: an array of just int values // post: return an ArrayList containing all the values public static ArrayList createNumbers(int[] rawNumbers) { ArrayList blo=new ArrayList(); for(int x:rawNumbers) blo.add(new Integer(x)); return blo; } // pre: an array of just Strings // post: return an ArrayList containing all the Strings public static ArrayList createMovies(String[] rawWords) { ArrayList blo=new ArrayList(); for(String x:rawWords) blo.add(new String(x)); return blo; } // pre: ArrayList a is not empty and contains only Integer objects // post: return the number of negative values in the ArrayList a public static int countNeg(ArrayList a) { int y=0; for(Integer x:a) if(x.compareTo(0)<0) y++; return y; } // pre: ArrayList a is not empty and contains only Integer objects // post: return the average of all values in the ArrayList a public static double average(ArrayList a) { int y=0; for(Integer x:a) y=y+x; return y/(a.size()-1); } // pre: ArrayList a is not empty and contains only Integer objects // post: replaces all negative values with 0 public static ArrayList replaceNeg(ArrayList a) { int g=0; for(Integer x:a) { if(x.intValue()<0) a.set(g,new Integer(0)); g++; } return a; } // pre: ArrayList a is not empty and contains only Integer objects // post: deletes all negative values in the ArrayList a public static ArrayList deleteZero(ArrayList a) { Iterator t=a.iterator(); while(t.hasNext()) if(t.next().intValue()==0) t.remove(); return a; } // pre: ArrayList a is not empty and contains only String objects // post: return ArrayList without duplicate movie titles public static ArrayList removeDupes(ArrayList a) { int g=0; Iterator t=a.iterator(); while(t.hasNext()) { if(t.next()==a.get(g)) t.remove(); g++; } return a; } }