/** *Author: Craig Supples *Course: CSC 330 *hw1 1 due 1/27/2014 *This is my own work. * */ class jcsupple_hwk1 { /** * Interface: Test * Test interface to be implemented by other methods * The ok method determines if the given item is "ok" as decided by the * implementation * @param */ public static interface Test //Test interface to be implemented by other methods { boolean ok(T item);// determines if item is "ok"(to be determined by method) } /** * Method: contains * Contains iterates through each item in the array and see if they're "ok" * according to the implementation of the method * @param * @param input * @param k * @return boolean, false if not in array, true if it is */ public static boolean contains(T[] input, Test k) { boolean found = false; for(int i = 0; found == false && i { public boolean ok(Integer k) { return(k < 0); } } /** * Class: Prime * Implementation: ok checks if element is prime number. Negatives, 0 and 1 * are not considered prime numbers. For 2 through the element's square root * it checks if there is a remainder, if there is ever no remainder then the * number is not prime. */ public static class Prime implements Test { public boolean ok(Integer k) { if (k <= 1) return false; for(int i = 2; i<=Math.sqrt(k);i++) { if((k % i) == 0) { return false; } } return true; } } /** * Class: PerfectSquare * Implementation: ok checks if integers less than given element, * when squared are equal to it. If so, it is a Perfect Square and true * is returned. If not, false is returned. */ public static class PerfectSquare implements Test { public boolean ok(Integer k) { for(int i = 1; (i*i)<=k; i++) { if((i*i) == k ) { return true; } } return false; } } /** * Main method: Creates an Integer array input that contains numbers to test * the effectiveness of the classes and if they are properly implemented. * The output should be true, false, true and false, true, true */ public static void main(String[] args) { Integer[] input = {100,37,49}; boolean result1 = contains(input, new Prime()); boolean result2 = contains(input, new Negative()); boolean result3 = contains(input, new PerfectSquare()); System.out.println("Is prime? "+result1); System.out.println("Is negative? "+result2); System.out.println("Is perfect square? "+result3); Integer[] input2 = {0,-10,9,27}; result1 = contains(input2, new Prime()); result2 = contains(input2, new Negative()); result3 = contains(input2, new PerfectSquare()); System.out.println("Is prime? "+result1); System.out.println("Is negative? "+result2); System.out.println("Is perfect square? "+result3); } }