/*********************************************** * CS2510 Fall 2011 * Lecture #20 * Selectors, Loops, Traversals, Statics, Exceptions ***********************************************/ import java.util.ArrayList; import tester.*; interface ISelect { // Is it selected by this selector? boolean select(T t); } class Traversal { private ArrayList list; private int index; Traversal(ArrayList list) { this.list = list; this.index = 0; } private Traversal(ArrayList list, int index) { this.list = list; this.index = index; } // Returns the current element in our Traversal T first() { return list.get(index); } // Increments our Traversal Traversal rest() { if (isEmpty()) { throw new TraversalException("Index out of bounds"); } else { return new Traversal(list,index + 1); } } // isEmpty: Are we at the end of our Traversal boolean isEmpty() { return (index >= list.size()); } } // Some algorithms class Algos { // Recursive sum function static int sum(ArrayList list) { // Base Case: Acc = 0 return sumH(new Traversal(list),0); } static int sumH(Traversal t, int acc) { if (t.isEmpty()) { return acc; } else { return sumH(t.rest(),t.first() + acc); } } // sum : With while loop static int sumw(ArrayList list) { Traversal t = new Traversal(list); int acc = 0; while(! t.isEmpty()) { acc = acc + t.first(); t = t.rest(); } return acc; } // sum : With for loop static int sumf(ArrayList list) { int acc = 0; for(Traversal t = new Traversal(list); ! t.isEmpty(); t = t.rest()) { acc = acc + t.first(); } return acc; } } class TraversalException extends RuntimeException { TraversalException(String e) { super(e); } } class LectureExamples { ArrayList loi = new ArrayList(); LectureExamples() { loi.add(1); loi.add(2); loi.add(3); } void testTraversal(Tester t) { t.checkExpect(loi.get(0),1); Traversal tloi = new Traversal(loi); try { tloi=tloi.rest(); tloi=tloi.rest(); tloi=tloi.rest(); tloi=tloi.rest(); t.checkExpect(true,false); // Should never run } catch (TraversalException e) { System.out.println("My Program caused the following expected error: " + e); t.checkExpect(true,true); } } void testAlgos(Tester t) { t.checkExpect(Algos.sum(loi),6); } }