package eecs2030.test2; import java.util.ArrayList; import java.util.List; public class Test2H { /** * The size of the list required by the method Test2G.avg2 */ public static final int AVG2_LIST_SIZE = 2; private Test2H() { // empty by design } /** * Returns true if tf is false, and false if * tf is true. * * @param tf a boolean value * @return the opposite of tf */ public static boolean not(boolean tf) { return !tf; } /** * Given a list containing exactly 2 integers, returns the average of the * two integers. The list t is not modified by this method. * For example: * *
     * t            Test2F.avg2(t)
     * ---------------------------
     * [-5, 9]       2
     * [3, 3]        3
     * [12, 7]       9.5
     * 
* * @pre t is not null * * @param t * a list containing exactly 2 integers * @return * the average of the two values in t * @throws IllegalArgumentException * if the list does not contain exactly 2 integers */ public static double avg2(List t) { if (t.size() != 2) { throw new IllegalArgumentException("list size != 2"); } double t0 = t.get(0); double t1 = t.get(1); return (t0 + t1) / 2.0; } /** * Computes the sum of the values in the list t. * The list t is not modified by this method. * The sum of an empty list is zero. If the sum of the values * is greater than Integer.MAX_VALUE then * Integer.MAX_VALUE is returned. * If the sum of the values * is less than Integer.MIN_VALUE then * Integer.MIN_VALUE is returned. * * @param t a list of values * @return the sum of the values in t * @pre t is not null */ public static int sum(List t) { long sum = 0; for (int i : t) { sum += i; } if (sum > Integer.MAX_VALUE) { sum = Integer.MAX_VALUE; } else if (sum < Integer.MIN_VALUE) { sum = Integer.MIN_VALUE; } return (int) sum; } /** * Returns a new list consisting of the individual digits of the number n. * For example: * *
     * n                 Test2H.fromInt(n)
     * -----------------------------------
     *  0                 [0]
     * -25                [-2, 5]
     * 9876543            [9, 8, 7, 6, 5, 4, 3]
     * 
* * @param n a number * @return a list consisting of the individual digits of the number n */ public static List fromInt(int n) { String s = "" + n; List t = new ArrayList(); int i = 0; char c = s.charAt(0); boolean isNeg = false; if (c == '-') { i = 1; isNeg = true; } for (; i < s.length(); i++) { c = s.charAt(i); t.add(Integer.valueOf("" + c)); } if (isNeg) { t.set(0, -t.get(0)); } return t; } public static void main(String[] args) { // not boolean tf = true; System.out.println( String.format("not(%b) : ", tf) + Test2H.not(tf)); // negate2 List t = new ArrayList(); t.add(3); t.add(5); System.out.println( String.format("avg2(%s) : %s", t.toString(), Test2H.avg2(t))); // sum t.clear(); t.add(4); t.add(5); t.add(6); t.add(7); t.add(8); System.out.println( String.format("sum(%s) : %d", t.toString(), Test2H.sum(t))); // fromInt int n = 1234; System.out.println( String.format("fromInt(%d) : %s", n, Test2H.fromInt(n))); } }