/* * Kendall Pitts * CSC 330 - HW1 * January 26, 2014 */ public class klpitts_hwk1 { public static void main(String[] args) { Integer[] input = {100, 37, 49, -16}; boolean result1 = contains(input, new Prime()); boolean result2 = contains(input, new PerfectSquare()); boolean result3 = contains(input, new Negative()); System.out.println(result1 + ", " + result2 + ", " + result3); } /** * The contains method checks all values contained in the array. * @param T[] input The array. * @param Check c The class to check the values against. * @return True, if one value in each set is true. */ public static boolean contains(T[] input, Check c) { boolean result = false; for (int i = 0; i < input.length; i++) { result = c.ok(input[i]); if (result) return true; } return result; } static public interface Check { /** * The ok method checks whether the value is prime, a perfect square, or * negative. * @param T item The value to check. * @return True or false, depending on the result of the check. */ boolean ok( T item); } static public class Negative implements Check { /** * This ok method checks whether the value is negative. * @param Integer val The value to check. * @return True, if the value is negative. */ @Override public boolean ok( Integer val) { return val < 0; } } static public class Prime implements Check { /** * This ok method checks whether the value is prime. * @param Integer val The value to check. * @return True, if the value is prime. */ @Override public boolean ok( Integer val) { //0 and 1 are not considered prime if (val < 1) return false; //check remaining positive integers for (int i = 2; i < val; i++) { if (val % i == 0) return false; } return true; } } static public class PerfectSquare implements Check { /** * This ok method checks whether the value is a perfect square. * @param Integer val The value to check. * @return True, if the value is a perfect square. */ @Override public boolean ok( Integer val) { //cannot take square root of negative, //returns false instead of error for (int i = 0; i < val; i++) { if (i * i == val) return true; } return false; } } }