// CSE 143, Winter 2011, Marty Stepp // This program demonstrates the ArrayList class used with ints. // You have to declare it as ArrayList instead of . // Integer is a "wrapper" object around an int. import java.io.*; import java.util.*; public class ProcessFile2 { public static void main(String[] args) throws FileNotFoundException { ArrayList list = readFile("numbers.txt"); System.out.println("Sum: " + sum(list)); System.out.println("All elements : " + list); filterEvens(list); System.out.println("Without evens: " + list); } public static ArrayList readFile(String fileName) throws FileNotFoundException { ArrayList list = new ArrayList(); Scanner input = new Scanner(new File(fileName)); while (input.hasNext()) { int num = input.nextInt(); list.add(num); } return list; } // Returns the sum of all the elements in the list. public static int sum(ArrayList list) { int sum = 0; for (int i = list.size() - 1; i >= 0; i--) { int num = list.get(i); sum += num; } return sum; } // Removes any even numbers from the given array list. public static void filterEvens(ArrayList list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) { list.remove(i); i--; // needed in case there are consecutive even numbers } } } }