/** * * @author Hoa Nguyen * Homework 1 */ public class h_nguye4_hwk1 { public static boolean contains (T[] input, Check c) { //Loop through the array for (int i = 0; i < input.length; i++) { //Check if each number is prime, negative, or perfect square if (c.ok(input[i])) return true; } return false; } static public interface Check { boolean ok(T item); } static public class Negative implements Check { //Returns true if the number is negative public boolean ok(Integer val) { return val < 0; } } static public class PerfectSquare implements Check { //Returns true if the number is a perfect square public boolean ok(Integer item) { //Get the square root value of the number double val = Math.sqrt(item); //Check if the square root value is integer or decimal if (val == (int) val) return true; return false; } } static public class Prime implements Check { //Returns true if the number is a prime public boolean ok(Integer item) { if (item == 0 || item == 1 || item < 0) return false; if (item == 2) return true; //Find the square root value of the number int val = (int) Math.sqrt(item); //Loop from 2 to the square root value for (int i = 2; i <= val; i++) { //If there is no remainder than it's not a prime if (item % i == 0) return false; } return true; } } /** * @param args the command line arguments */ public static void main(String[] args) { Integer[] input = {100, 37, 49}; boolean result1 = contains(input, new Prime()); boolean result2 = contains(input, new Negative()); boolean result3 = contains(input, new PerfectSquare()); System.out.println(result1); System.out.println(result2); System.out.println(result3); } }