/* * This is my own work. * Dylan Stuart */ /* * Java program that provides the requirements described by exercise 4.42 * in the textbook. */ public class dcstuart_hwk1 { /** * Takes an array of arbitrary type and checks to see if * any items within it satisfy a certain condition. * * @param Data type of the items checked within the array * @param input an array of an arbitrary type * @param c a condition to check the array items for * @return true if an item within the array satisfies the condition, * otherwise false */ public static boolean contains(T[] input, Check c) { for (int i = 0; i < input.length; i++) { if (c.ok(input[i]) == true) { return true; } } return false; } /** * An interface that is used to specify the second parameter of * the contains method, * * @param The data type of the item being checked */ static public interface Check { boolean ok(T item); } /** * PerfectSquare class checks if Integer objects are perfect * squares. */ static public class PerfectSquare implements Check { @Override public boolean ok(Integer val) { double root = Math.sqrt(val); return val % root == 0; } } /** * Prime class checks if Integer objects are prime numbers. */ static public class Prime implements Check { @Override public boolean ok(Integer val) { for (int i = 2; i < val / 2; i++) { if (val % i == 0) { return false; } } return true; } } /** * Negative class checks if Integer objects are negative numbers. */ static public class Negative implements Check { @Override public boolean ok(Integer val) { return val < 0; } } /* * Main method is used to test the example results described in the book */ public static void main(String[] args) { Integer[] input = {100, 37, 49}; boolean result1 = contains(input, new Prime()); boolean result2 = contains(input, new PerfectSquare()); boolean result3 = contains(input, new Negative()); System.out.println(result1); System.out.println(result2); System.out.println(result3); } }