/** * I understand and accept the UNCG Academic Honor Codeļ¼Œthis is my * own work. * CSC330 - 01 * Rui Da * Student ID: 887-54-0493 */ package homework1; /** * This program iterates through every element of a given array, check * whether or not it contains prime, negative or perfect square elements. * @author Rui */ public class r_da_hwk1 { public static interface Type{ boolean check(T target); } /* * contains method checks an array to see whether or not it has prime, negative * or perfect square number. */ public static boolean contains(T[] targetArray, Type n){ boolean result = false; for (T element : targetArray) { if (n.check(element)) { result = true; } } return result; } /* * To check whether or not an element is a negative number. */ public static class Negative implements Type{ @Override public boolean check(Integer target){ return target < 0; } } /* * To check whether or not an element is a prime number. */ public static class Prime implements Type{ @Override public boolean check(Integer target){ boolean result = true; if (target < 2) return false; else{ for (int i = 2; i*i < target; i++){ if (target%i == 0){ result = false; break; } } return result; } } } /* * To check whether or not an element is a perfect square number. */ public static class PerfectSquare implements Type{ @Override @SuppressWarnings("empty-statement") public boolean check(Integer target){ boolean result = false; int i; for (i = 1; i*i < target; i++); if (target == i*i) result = true; return result; } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Integer[] input = { -1}; 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); } }