import static java.lang.Math.sqrt; /** * This is my own work: Chris Murphy * CSC 330 : Lixin Fu * 1/27/14 * Class which checks arrays for certain characteristics. */ public class ctmurphy_hwk1 { /** * Checks an array * * @param input of generic type * @param for the * @param cond specified and then * @return true if the condition is met by any of the items in the array, * false otherwise. */ public static boolean contains(T[] input, Condition cond) { //loops through items in array checking each for the condition for (int i = 0; i < input.length; i++) { //returns true if condition is met if (cond.check(input[i])) { return true; } } //returns false if condition is not met. return false; } /** * Interface for implementing on conditions which * * @param is to be checked for. */ static public interface Condition { /** * This method will check * * @param item for the condition specified in this implementation * @return true if condition is met, false otherwise */ boolean check(T item); } static public class Negative implements Condition { /** * Checks * * @param num to see if it is a negative number. * @return true if @param num is negative, false otherwise */ public boolean check(Integer num) { //returns true if num is less than 0, false otherwise return num < 0; } } static public class Prime implements Condition { /** * Checks to see if * @param num is a prime number. * @return true if @param nuym is prime, false otherwise */ public boolean check(Integer num) { //check for any factors of num between 2 and square root of num for (int i = 2; i < sqrt(num); i++) { //if i is a factor of num, num isn't prime, return false if (num % i == 0) { return false; } } //no numbers between 2 : sqrt(num) were factors of num, num is prime return true; } } static public class PerfectSquare implements Condition { /** * * Checks to see if * @param num is a perfect square. * @return true if @param num is a perfect square, false otherwise */ public boolean check(Integer num) { //create a test variable for checking all perf squares up to num int m = 0; //loop increments m to check each perf square less than num while (m * m < num) { m++; } //if num equals the m*m then num is next perf square, return true if ((m * m) == num) { return true; //otherwise, next perf square is >num so not num, so return false } else { return false; } } } public static void main(String[] args) { //create array to test contains method Integer[] test = {100, 7919, 49}; //tests each implementation of Condition, uses contains to check for con boolean result1 = contains(test, new Negative()); boolean result2 = contains(test, new Prime()); boolean result3 = contains(test, new PerfectSquare()); //print the results System.out.println(result1); System.out.println(result2); System.out.println(result3); } }