/** * * Eric Nursey 10/25/2014 This is my own work. * */ class esnursey_hw1 { //checks to see if the array contains the requested type of value public static boolean contains(T[] input, check c) { //checks each value of the array for (int i = 0; i < input.length; i++) { //returns true if the check is correct if (c.isOK(input[i])) { return true; } } return false; } //Interface to be used by prime, negative, and perfectsquare public static interface check { boolean isOK(T item); } //Checks to see if the given value is prime public static class Prime implements check { @Override public boolean isOK(Integer val) { //1-3 are prime, so skip them if (val < 4) { return true; } //for 4 and up, divide by all numbers BETWEEN 1 and the value else { for (int i = 2; i < val; i++) { if (val % i == 0) { return false; } } } return true; } } //Checks to see if the given value is a perfect square public static class PerfectSquare implements check { @Override public boolean isOK(Integer val) { //checks numbers up to the value for (int i = 1; i <= val; i++) { //if the number times itself is the value, it is a square if (i * i == val) { return true; }//stops the loop if the squared value is above the sought value else if (i * i > val) { return false; } } return false; } } //Checks to see if the value is negative public static class Negative implements check { @Override public boolean isOK(Integer val) { //checks if the value is negative return val < 0; } } 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 + " " + result2 + " " + result3); } }