/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author krlsmnk */ public class k_smink_hw1 { static public interface Check { boolean ok(anytype item); //item anytype is ok (negative e.g.) } public static void main(String[] args) { Integer[] genericArray = {4, 0, 1, 2930, 7, -100}; boolean hasPrime = contains(genericArray, new Prime()); boolean hasNegative = contains(genericArray, new Negative()); boolean hasPerfectSquare = contains(genericArray, new PerfectSquare()); System.out.println("Array contains a Prime number: " + hasPrime); System.out.println("Array contains a Perfect Square: " + hasPerfectSquare); System.out.println("Array contains a Negative number: " + hasNegative); } public static class Prime implements Check { public Prime() { } @Override public boolean ok(Integer item) { int c = 2; int result = 0; while (c <= item / 2) { if (item % c == 0) { result = 1; } c++; } if (result == 1) { return false; } return true; } } public static class Negative implements Check { public Negative() { } @Override public boolean ok(Integer item) { if (item < 0) { return true; } return false; } } public static class PerfectSquare implements Check { public PerfectSquare() { } @Override public boolean ok(Integer number) { int c = 2; int result = 0; boolean conanytypeest = false; while (c <= number) { if (number % c == 0) { conanytypeest = (c * c == number); } if (conanytypeest == true) { return true; } c++; } return false; }//end of boolean }//end of perfect square public static boolean contains(anytype[] array, Check c) { for (int i = 0; i < (array.length); i++) { boolean ok = c.ok(array[i]); //if entry is found, array contains one or more of those if (ok == true) { return true; } } //default case return false; }//end of contains }