import java.util.*; class LoopDemo { /* Return the sum of the numbers in `data`. */ static double sum_v1( List data ) { if (data.isEmpty()) { return 0.0; } else { return data.get(0) + sum_v1(data.subList(1,data.size())); } } static boolean foo( String s, int... nums ) { return (nums.length > 3); } /* Return the sum of the numbers in `data`. */ // static double sum_v2( List data ) { double sumSoFar = 0.0; while (!data.isEmpty()) { sumSoFar = sumSoFar + data.get(0); data = data.subList(1,data.size()); } return sumSoFar; } /* Return the smallest of the numbers in `data` * (or the sentinel -inf.0 if empty -- arguably a poor choice). */ static double min_v2( List data ) { double minSoFar = data.get(0); while (!data.isEmpty()) { minSoFar = Math.min( minSoFar, data.get(0) ); data = data.subList(1,data.size()); } return minSoFar; } /* Return a list of numbers from n..1. */ static List numsDown( int n ) { if (n==0) { return new LinkedList(); } else { /* return numsDown(n-1).add(0, (double)n);*/ List restNumsDown = numsDown(n-1); restNumsDown.add(0, (double)n); // `add` is a void method, so I can't combine with the preceding or following line. return restNumsDown; } } /* Return all the strings in `strs` appended with a space, * followed by "whoa". */ static String stringAppendWhoa( List strs ) { String resultSoFar = "whoa"; while (!strs.isEmpty()) { resultSoFar = strs.get(0) + " " + resultSoFar; strs = strs.subList(1,strs.size()); } return resultSoFar; } public static void main( String[] args ) { System.out.println( foo( "hello", 2, 4, 7, 99, -1 ) ); System.out.println( foo( "hello", 2, 4 ) ); System.out.println( "Expect: 0. Got: " + sum_v1( new ArrayList() )); System.out.println( "Expect: 12. Got: " + sum_v1(Arrays.asList( 5.0, 2.0, 4.0, 1.0 )) ); System.out.println( "Expect: 0. Got: " + sum_v2( new ArrayList() )); System.out.println( "Expect: 12. Got: " + sum_v2(Arrays.asList( 5.0, 2.0, 4.0, 1.0 )) ); System.out.println( "Expect: \"hi bye aloha whoa\". Got: " + "\"" + stringAppendWhoa( Arrays.asList("hi","bye","aloha") ) + "\"" ); } }