/** * This is my own work: Sarah Harris CSC 330 homework 1 Determining if an * entered value is negative, prime and/or a perfect square * */ public class Hw1_882792021 { // creates interface for three classes to implement static public interface Specify { // takes in T value to convert to generic, boolean result public boolean specify(T val); } public static void main(String[] args) { // example code from question in book Integer[] input = {100, 37, 49}; boolean result1 = contains(input, new Prime()); boolean result2 = contains(input, new PerfectSquare()); boolean result3 = contains(input, new Negative()); // output the results of each test System.out.println(result1); System.out.println(result2); System.out.println(result3); } public static boolean contains(T[] input, Specify val) { // creates default result to false boolean result = false; // runs a for loop to go through whole array for (int i = 0; i < input.length; i++) { // keeps checking for a true result until one is found if (result != true) { // calls the numerical value into the class choosen in main result = val.specify(input[i]); } } // if one is not found, a false result will occur return result; } static public class Prime implements Specify { @Override public boolean specify(Integer val) { // 2 is a 'special prime', always put value to true if (val == 2) { return true; } // keeps modding the number up until one less its value // if a value other than itself has a mod of 0, false will occur for (int i = 2; i <= val - 1; i++) { if (val % i == 0) { return false; } } // returns false iff val % val is 0 , nothing else return true; } } static public class PerfectSquare implements Specify { @Override public boolean specify(Integer val) { // first takes squre root of val, then mods by one // if result is 0, its a perfect square, false otherwise return Math.sqrt(val) % 1 == 0; } } static public class Negative implements Specify { @Override public boolean specify(Integer val) { // if the val is less than 0, its a negative return val < 0; } } }