/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Sam Huggins */ public class hwk1 { public static void main(String[] args) { //Array to be tested int input[] = {100,37,49}; //The various calls to the contains method with the different test //to be done one each element boolean result1 = contains (input, new Prime()); boolean result2 = contains (input, new Negative()); boolean result3 = contains (input, new PerfectSquare()); } //Method used for instantiating the different classes needed for testing //the array private static boolean contains(int[] input, Check c) { int i = 0; //Loop for testing each array element while(i < input.length) { boolean answer = c.ok(input[i]); System.out.println(answer + "\n"); i++; } return false; } public static interface Check { boolean ok( T item); } public static class Prime implements Check { @Override public boolean ok(Integer val) { System.out.println("Is " + val + " prime?"); //Test if val is a prime number, if it's divisible by 2 then //it's not or if it's divisible by any odd number less then itself, //then it's also not prime if (val%2 == 0) return false; for(int i = 3; i*i <= val; i+=2) { if(val%i == 0) return false; } return true; } } public static class Negative implements Check { @Override public boolean ok(Integer item) { System.out.println("Is " + item + " negative?"); //If item is less then zero its negative return item < 0; } } public static class PerfectSquare implements Check { @Override public boolean ok(Integer val) { System.out.println("Is " + val + " a perfect square?"); //Convert val into a double and test it using the math function Double number = (double) val; double sqr = Math.sqrt(number); return (sqr-Math.floor(sqr)== 0); } } }