/** * CSC 330 * Homework 1 * @author Austin Macdonald * I have abided by the UNCG Academic Integrity Policy on this assignment. */ class asmacdon_hwk1 { /** * Checks each item in an array for a desired trait. * @param input A generic array to check. * @param c An object that indicates the desired trait to check. * @return true if the array contains at least one instance of the trait c. */ public static boolean contains(T[] input, Check c) { // Iterate through the array for (T item: input) { // Check each item based on the type of c. if (c.ok(item)) { return true;} } // Did not contain any instances, return false. return false; } /** * Each trait class must have a method to check whether an item is that trait. */ static public interface Check { /** * @return true if * @param item fulfills the requirements of this trait. */ boolean ok(T item); //item T is ok(negative eg) } /** * Perfect Square class tests whether an integer is a perfect square. */ static public class PerfectSquare implements Check { /** * @return true iff * @param val is a perfect square */ public boolean ok( Integer val) { double sqrt = Math.sqrt(val); return (sqrt == Math.floor(sqrt)); } } /** * Checks whether an iteger is negative */ static public class Negative implements Check { /** * @return true iff * @param val is a negative number. */ public boolean ok( Integer val) { return val < 0; } } /** * Checks whether an integer is a prime number */ static public class Prime implements Check { /** * @return true iff * @param val is a prime number */ public boolean ok( Integer val) { // Primes can only be positive. if (val < 0) { return false;} // Check that each number is not evenly divisibly by any number // between 1 and the number(exclusive). for (int i = 2; i < val; i++) { if (val % i == 0) {return false;} } return true; } } // Create an array and test each class and its 'ok' method. public static void main(String[] args) { Integer [] input = {7}; boolean result1 = contains(input, new Negative()); boolean result2 = contains(input, new PerfectSquare()); boolean result3 = contains(input, new Prime()); System.out.println(result1); System.out.println(result2); System.out.println(result3); } }